Dashboard Agent: investigations, watches, alerts, and notifications - #4418
Dashboard Agent: investigations, watches, alerts, and notifications#4418kathiekiwi wants to merge 168 commits into
Conversation
…signals Gauges are read inside the enqueue/dequeue Lua and returned on the script reply as a 2-tuple; counters are cumulative odometers. The run-queue Redis carries no metrics stream of its own.
…counters entryOrderKey returns a string built with BigInt math so ordering stays correct at real epoch magnitudes. Odometer keys are namespaced by definition name. The consumer reports null lag for a missing consumer group instead of 0, and empty gauge values parse as NaN rather than 0.
…ng order keys The wait-time quantile materialized view now excludes wait_ms = 0 rows so it matches the count aggregation. order_key accepts a string or a number. Migration comments no longer contain semicolons that split the migration into invalid statements.
…rride The queues list tolerates a metrics query failure by rendering without metrics and logging a warning. UsageSparkline renders its total override even when every bucket is zero. The queue detail page returns 404 and its loader skips the metrics query when the feature flag is off. The seed script validates bucket size and only writes ClickHouse against a local host.
A bucket-led ORDER BY DESC combined with fillGaps emitted an ascending WITH FILL (positive step, ascending bounds), which produces invalid or empty fills. Skip the gap-fill rewrite for descending orders and let the plain descending query stand. Adds a DESC fillGaps test.
Packs the stream sequence with a 1e6 factor (was 1e5) so up to 1M entries per millisecond per shard fit before a seq could spill into the next millisecond's range, far above what a single Redis stream can produce. ms*1e6 stays within UInt64. Also fixes the webapp mapping test that still expected a numeric order_key after the switch to a BigInt-derived string.
The queues list and queue detail pages now use the shared TimeFilter (any preset period or a custom date range) and everything on the page follows it: header tiles, per queue metric columns, charts, and stats. The custom period buttons, hand rolled chart cards, and duplicated metric fetch loops are replaced by the ChartCard and Chart primitives, UsageSparkline, and a shared useMetricResourceQuery hook. The ClickHouse list queries take an explicit end bound so fixed ranges query only their window.
Queries using deltaSumTimestampMerge failed with an unknown function error, which broke the queue detail stats and the started counts on the built in Queues dashboard.
The queues list header tiles now render the same line chart, grid, and tooltip as the rest of the metrics charts instead of a row sparkline, with the headline value in the tile header. The env saturation tile draws the environment concurrency limit and burst limit as labeled reference lines. Chart tooltips keep a gap between the series label and the value, and the shared line chart gains showDots and referenceLines options.
Adds an Allocation tab to the Queues page (behind the queue metrics UI flag): overview cards, a burst-aware capacity bar showing each queue allocation and its live usage in a distinct color, an inline-editable limits table with per-queue locks, load-weighted auto-balance, and a review dialog that bulk-applies limits as overrides through the existing concurrency system. The queue list now defaults to Busiest ordering (with Backlog and Name options). ClickHouse ranks queues by activity over the last 15 minutes and returns just the requested page of names, so the cost per page is one small aggregate regardless of environment size; idle queues follow in name order and any failure falls back to name ordering. The classic page keeps plain name order.
The fallback WHERE injection only targeted the top-level SELECT, so a query shaped as an outer aggregation over a FROM subquery failed to compile: the time column only exists inside the subquery. Descend into the subquery so the fallback lands next to the table reference.
Adds two rollups fed from the raw landing table: a per-queue 5-minute tier and an environment-level 1-minute tier (gauges plus TDigest wait quantiles). Ranking now reads the 5m tier and returns the page and the ranked total in one windowed query instead of two scans. The 5m materialized view reads raw rather than cascading off the 10s table: deltaSumTimestamp states hold a single first/last segment, so merging states in an MV's hash-ordered GROUP BY double-counts bridging spans. For the same reason the env tier carries no counter columns, and env-wide counter totals must group by queue before summing.
The built-in queues dashboard's enqueued vs started chart merged counter states across queues, which mixes unrelated cumulative counters and returns wrong totals; it now merges per queue and sums outside. Env header tiles and saturation charts read the environment rollup, so their cost no longer scales with queue count, and coarse-bucket ranges are served from the 5m rollup automatically. Queue list ranking runs as one query, time bounds are aligned to the bucket grid, and repeated auto-refresh reads share ClickHouse query-cache entries.
… rollup The env rollup's win comes from dropping the queue dimension, not from coarser buckets: row count is queue-independent (~8640/day/env), so full 10-second granularity stays cheap at any range. Env header tiles and saturation charts now resolve short-range detail exactly like the per-queue charts, and the current-value tiles read the latest 10-second bucket instead of a minute-wide one.
The simulator's --reset only cleared the raw and 10s tables, leaving stale rows in the 5m and env rollups. It also force-merges the rollups after seeding so current-value widgets read cleanly.
…aks plainly One conversational message with the watch's note, a lime CTA, and the same skeleton as the billing-limit email; the fielded fact sheet is gone and the unsubscribe link keeps its wiring with footer styling.
…d to mid-column, number in the value column
'Watch update — all clear / needs your attention', toned by kind; the identity moves to the details line and the subject follows suit.
…with starred scenarios
|
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (3)
🚧 Files skipped from review as they are similar to previous changes (1)
📜 Recent review details⏰ Context from checks skipped due to timeout. (33)
🧰 Additional context used📓 Path-based instructions (6)**/*.{ts,tsx}📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Files:
{packages/core,apps/webapp}/**/*.{ts,tsx}📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Files:
**/*.{ts,tsx,js,jsx}📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Files:
apps/webapp/**/*.{ts,tsx}📄 CodeRabbit inference engine (.cursor/rules/webapp.mdc)
Files:
apps/**/*.{ts,tsx}📄 CodeRabbit inference engine (AGENTS.md)
Files:
apps/webapp/app/**/*.{ts,tsx}📄 CodeRabbit inference engine (apps/webapp/CLAUDE.md)
Files:
🧠 Learnings (16)📚 Learning: 2026-02-11T16:37:32.429ZApplied to files:
📚 Learning: 2026-07-28T21:57:20.061ZApplied to files:
📚 Learning: 2026-03-22T13:26:12.060ZApplied to files:
📚 Learning: 2026-03-22T19:24:14.403ZApplied to files:
📚 Learning: 2026-05-18T08:21:27.694ZApplied to files:
📚 Learning: 2026-05-18T08:21:27.694ZApplied to files:
📚 Learning: 2026-06-13T19:53:13.759ZApplied to files:
📚 Learning: 2026-06-17T17:13:49.929ZApplied to files:
📚 Learning: 2026-06-23T13:04:21.413ZApplied to files:
📚 Learning: 2026-04-16T14:21:15.229ZApplied to files:
📚 Learning: 2026-05-08T21:00:20.973ZApplied to files:
📚 Learning: 2026-06-25T18:21:55.847ZApplied to files:
📚 Learning: 2026-05-12T21:04:05.815ZApplied to files:
📚 Learning: 2026-06-25T18:21:51.905ZApplied to files:
📚 Learning: 2026-07-03T17:10:21.498ZApplied to files:
📚 Learning: 2026-06-25T18:21:54.729ZApplied to files:
🔇 Additional comments (2)
WalkthroughThis PR introduces a comprehensive Dashboard Agent feature: a new contracts package defining shared schemas for view blocks, intents, page context, watches, and trigger:// URIs; a dedicated database package for chats, investigations, and watches; core agent tool/prompt logic including investigation rendering, docs search, and navigation intents; a watch-tick lifecycle with checks, alerts (email/Slack/webhook), and unsubscribe flows; new API routes for watches, alerts, queue metrics, and run diagnostics; a redesigned chat panel UI with investigation/report/watch cards, suggested prompts, and unread-wake notifications; a Storybook demo gallery with screenshot tooling; seed scripts; and removal of "Docs" links from numerous page headers across the webapp. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
…t button; URLs are links The prompt now treats earlier turns' pages as history — deictic questions re-read the current page every turn, and page explanations end with a matching docs link. The report's contact action falls back to the contact page as a real external button instead of an ask round-trip, and answers that point at a URL carry it as a link.
…ress line, wake toast opens its chat as an agent Callout - navigate intents and navigate_to outputs resolve trigger:// URIs server-side and navigate in place; same-origin citation buttons navigate instead of opening a new tab. - The transcript autoscrolls on send and follows streaming near the bottom; a store-order stable merge stops messages landing mid-chat after a page change (server-side single-read follow-up noted). - The generic Working line yields to a tool-specific one. - The wake toast is the new agent Callout variant (chat icon) and opens the exact chat that woke.
…nside the label column
An in-flight tool call now shows a compact pill (per-tool phrase + spinner, watch-chip visual language) instead of raw streaming JSON — covering render_view and get_report, the biggest offenders. Completed and error states render as before; gallery in-flight examples reworked and a pill line-up section added.
The answer is the prose and the cards, never the input/output plumbing: a landed call disappears (the pill was its only trace), and only a FAILED call keeps its error row. Gallery example reworked accordingly.
Wakes are wake-shaped (banner renders), no prose points at tool rows that no longer render, footer-era phrasing removed, the four-wake variation matrix became one coherent story, and tests now enforce all of it (wake ids parse via the real WakeBanner, removed-UI phrases are banned).
Offering to fetch what a tool can fetch now is banned; 'how do I check X' about the user's project gets both the how-to and the actual check; only genuinely unreachable steps (their infra, their code, external pages) go to the user, clearly separated.
…flows # Conflicts: # .changeset/report-health.md # .server-changes/agent-detail-metrics-layout.md # .server-changes/paginate-concurrency-keys-table.md # .server-changes/queue-metrics-dashboard.md # apps/webapp/app/components/dashboard-agent/AgentChart.tsx # apps/webapp/app/components/metrics/MiniLineChart.tsx # apps/webapp/app/components/query/QueryEditor.tsx # apps/webapp/app/env.server.ts # apps/webapp/app/hooks/useMetricResourceQuery.ts # apps/webapp/app/presenters/v3/QueueListPresenter.server.ts # apps/webapp/app/presenters/v3/QueueMetricsPresenter.server.ts # apps/webapp/app/presenters/v3/RunQueueMetricsPresenter.server.ts # apps/webapp/app/presenters/v3/reports/health/health-data.ts # apps/webapp/app/presenters/v3/reports/health/health-messages.ts # apps/webapp/app/presenters/v3/reports/health/health.ts # apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.query/ExamplesContent.tsx # apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.query/TableSchemaContent.tsx # apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.queues/route.tsx # apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.queues_.$queueParam/route.tsx # apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.tasks.standard.$taskParam/route.tsx # apps/webapp/app/routes/api.v1.query.schema.ts # apps/webapp/app/routes/resources.metric.tsx # apps/webapp/app/routes/resources.orgs.$organizationSlug.projects.$projectParam.env.$envParam.query.ai-generate.tsx # apps/webapp/app/routes/resources.orgs.$organizationSlug.projects.$projectParam.env.$envParam.runs.$runParam.spans.$spanParam/route.tsx # apps/webapp/app/routes/resources.queues.concurrency-keys.ts # apps/webapp/app/services/queryService.server.ts # apps/webapp/app/v3/querySchemas.ts # apps/webapp/app/v3/queueMetrics.server.ts # apps/webapp/test/reportHealth.test.ts # internal-packages/clickhouse/src/client/tsql.ts # internal-packages/run-engine/src/engine/systems/enqueueSystem.ts # internal-packages/tsql/src/query/schema.ts
@trigger.dev/build
trigger.dev
@trigger.dev/core
@trigger.dev/python
@trigger.dev/react-hooks
@trigger.dev/redis-worker
@trigger.dev/rsc
@trigger.dev/schema-to-json
@trigger.dev/sdk
commit: |
… uses the tenancy-scoped list signature The suite pinned a migration list that stopped before last_read_at (42703 on CI) and two tests still called listActiveWatchesForChats with the pre-tenancy array signature. Migrations are now read from the folder so a new one can't silently stale the schema.
There was a problem hiding this comment.
Actionable comments posted: 8
Note
Due to the large number of review comments, Critical, Major severity comments were prioritized as inline comments.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam/route.tsx (1)
95-112: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick winGuard
getPromotedDashboardAgentPromptagainst failures, and skip it when access is already false.This loader backs the entire env layout (
Outletwraps every page under this environment), so it runs on nearly every navigation.getPromotedDashboardAgentPromptis called unconditionally and unguarded — if flag evaluation/parsing ever throws, it takes down the whole environment layout for a feature that's purely cosmetic (a suggested-prompt chip). It's also wasted work wheneverhasDashboardAgentAccessisfalse, sinceDashboardAgentnever consumespromotedPromptin that case (it early-returns children without rendering the panel).🛡️ Proposed fix: gate on access and fail closed
- const promotedDashboardAgentPrompt = await getPromotedDashboardAgentPrompt({ - orgFeatureFlags: (project.organization.featureFlags as Record<string, unknown>) ?? {}, - }); + const promotedDashboardAgentPrompt = hasDashboardAgentAccess + ? await getPromotedDashboardAgentPrompt({ + orgFeatureFlags: (project.organization.featureFlags as Record<string, unknown>) ?? {}, + }).catch((error) => { + logger.error("Failed to resolve promoted dashboard agent prompt", { error }); + return undefined; + }) + : undefined;
🟡 Minor comments (13)
apps/webapp/seed-agent-examples.mts-1598-1614 (1)
1598-1614: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
?.value ? … : undefinedcollapses a legitimate zero into the fallback.
pending,donePerMin,triggeredPerMinanddrainMinutesall treat a reported0as "absent" and fall back to theSTORY.*constants. On a recovered or quiet stand the card would read 0 pending while the prose quotes 4,812 — the exact disagreement this function exists to prevent. Use a nullish check instead.🐛 Guard on presence, not truthiness
- pending: metric("pending")?.value ? Math.round(metric("pending")!.value) : undefined, + pending: metric("pending")?.value != null ? Math.round(metric("pending")!.value) : undefined, worstQueueShare: flow?.attribution?.dim === "queue" ? flow.attribution.share : undefined, - donePerMin: vm.facts?.throughput?.donePerMin + donePerMin: vm.facts?.throughput?.donePerMin != null ? Math.round(vm.facts.throughput.donePerMin) : undefined, - triggeredPerMin: vm.facts?.throughput?.triggeredPerMin + triggeredPerMin: vm.facts?.throughput?.triggeredPerMin != null ? Math.round(vm.facts.throughput.triggeredPerMin) : undefined, - drainMinutes: drain?.value ? Math.round(drain.value) : undefined, + drainMinutes: drain?.value != null ? Math.round(drain.value) : undefined,apps/webapp/seed-queue-metrics.mts-581-597 (1)
581-597: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win
DELETEwithoutmutations_syncraces the seeding insert that follows.
--resetruns these deletes and then line 941 inserts immediately. The sibling seeder guards the identical sequence withSETTINGS mutations_sync = 2and explains why: left asynchronous, the re-seed races its own predecessor and leaves a second copy of the data behind. Worth settingasync_insert: 0on line 572 too, so the rows are visible to theOPTIMIZE … FINALcalls on lines 949-952.🐛 Make the reset finish before seeding
await raw.command({ - query: `DELETE FROM trigger_dev.${table} WHERE environment_id = '${environmentId}'`, + query: `DELETE FROM trigger_dev.${table} WHERE environment_id = '${environmentId}' SETTINGS mutations_sync = 2`, });apps/webapp/seed-agent-examples-chats.mts-338-339 (1)
338-339: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winUse the
COMPLETED_WITH_ERRORSstatus literal in the TRQL query.
Failedis not a standard run status in Trigger.dev TRQL; usestatus = 'COMPLETED_WITH_ERRORS'so the seeded failed runs are counted.apps/webapp/seed-queue-metrics.mts-1-6 (1)
1-6: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick winKeep this seeder consistent with
seed-agent-examples.mts's documented interop pattern.
seed-agent-examples.mtsdisables the sibling import-entry CommonJS boundary instead of running into the documented named-import loading failure, so this script should use the same default-binding import/interworking pattern.internal-packages/dashboard-agent-contracts/src/blocks.ts-133-146 (1)
133-146: 🔒 Security & Privacy | 🟡 Minor | ⚡ Quick winRequire
http(s)on docs action targets.
targetis documented as “an https URL” fordocsactions, but the schema accepts any string. Since this field is LLM-authored UI input, prefer narrowing it tohttp://orhttps://URLs in the schema rather than leaving the contract to later validation.apps/webapp/app/services/dashboardAgentWatchChecks.ts-146-175 (1)
146-175: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winMake unreliable queued wait labels include the stale-first-enqueue caveat.
For
WAITING_TO_RESUME/RETRYING_AFTER_FAILURE/PAUSED,run.queuedAtis not a current queue entry, but this path still emitswaitBasis: "queued_at"and a confidentqueued for …label. Bake the caveat into the label or omit the label whenqueueWaitReliableis false so it can’t be surfaced as a current wait time downstream.♻️ Make the label carry its own caveat
if (run.queuedAt) { const waitMs = Math.max(0, end.getTime() - run.queuedAt.getTime()); return { waitMs, waitBasis: "queued_at", - waitLabel: `queued for ${formatMs(waitMs)}`, + waitLabel: queueWaitReliable + ? `queued for ${formatMs(waitMs)}` + : `time since first enqueue: ${formatMs(waitMs)}`, queueWaitReliable, }; }apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx-163-180 (1)
163-180: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
CitationButtonrenders different elements on server vs client.
pathis alwaysnullduring SSR, so the server emits aLinkButtonanchor while the first client render emits aButton— a hydration mismatch for every same-origin citation. Compute the path fromsameOriginPathafter mount (or keep one element type and branch insideonClick).♻️ One option: single element, branch on click
function CitationButton({ url, label }: { url: string; label: string }) { const navigate = useNavigate(); - const path = typeof window === "undefined" ? null : sameOriginPath(url, window.location.origin); - - if (path) { - return ( - <Button variant="docs/small" LeadingIcon={BookOpenIcon} onClick={() => navigate(path)}> - {label} - </Button> - ); - } - return ( - <LinkButton to={url} variant="docs/small" LeadingIcon={BookOpenIcon}> + <LinkButton + to={url} + variant="docs/small" + LeadingIcon={BookOpenIcon} + onClick={(event) => { + const path = sameOriginPath(url, window.location.origin); + if (!path) return; + event.preventDefault(); + navigate(path); + }} + > {label} </LinkButton> ); }apps/webapp/app/components/dashboard-agent/DashboardAgentPanel.tsx-166-189 (1)
166-189: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick winPost-mutation reloads can coalesce onto a pre-mutation request.
loadHistoryreturns the in-flight promise, so thevoid loadHistory()calls indeleteChat(Line 422) andcancelWatch(Line 452) can piggyback on a GET that was issued before the POST landed and re-render the stale list — the deleted chat reappears, or the cancelled watch chip comes back, until something else triggers a reload. Chain a fresh request after the in-flight one instead of returning it.🐛 Sketch: let callers ask for post-mutation freshness
- const loadHistory = useCallback(async () => { - if (historyInFlight.current) return historyInFlight.current; + const loadHistory = useCallback(async (options?: { fresh?: boolean }) => { + if (historyInFlight.current) { + // A reload after a mutation must not adopt a request that was already + // in flight before it — that result predates the change. + if (!options?.fresh) return historyInFlight.current; + await historyInFlight.current; + } const request = (async () => {Then call
void loadHistory({ fresh: true })fromdeleteChatandcancelWatch.apps/webapp/app/components/dashboard-agent/RunDiagnosisCard.tsx-161-177 (1)
161-177: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winAn enabled button that does nothing is a real click target outside the gallery.
useRunPathreturnsundefinedwhenever org/project/env context is missing — the storybook gallery is one such case, but any future host without that context is another. A user clicking gets silence with no feedback. Preferdisabled(or a tooltip explaining why) so the inert state is honest, and keep the gallery's visual review by passing an explicit prop rather than inferring it from missing context.apps/webapp/test/dashboardAgentWatchChecks.test.ts-123-134 (1)
123-134: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winAssert the label in the stale-
queuedAtcase — that's the invariant this file exists to pin.The header calls out the wait label as the thing that must never call a time-from-creation a queue wait, but this test only checks
queueWaitReliableandwaitBasis. A regression that emitted"queued for 10m"for an untrustworthyqueuedAton a resumed run would still pass. Add the label (and theresult) assertion.💚 Proposed addition
expect(outcome.facts.queueWaitReliable).toBe(false); expect(outcome.facts.waitBasis).toBe("queued_at"); + expect(outcome.result).toBe("pending"); + // Reliability is false, so the label must not claim a queue wait. + expect(outcome.facts.waitLabel).not.toMatch(/queued for/);internal-packages/dashboard-agent/src/tools.ts-429-448 (1)
429-448: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick winWrap the body read so an aborted/interrupted response doesn't escape as a throw.
The
fetchcall is guarded butawait res.text()on Line 431 is not. If the 30s abort fires while the body is streaming (or the connection resets mid-body), this rejects and the throw escapessearchTriggerDocs, breaking the documented "returns{ error }" contract thatsearch_docsrelies on.🛡️ Proposed fix
if (!res.ok) return { error: `The docs search failed (status ${res.status}).` }; - const body = await res.text(); + let body: string; + try { + body = await res.text(); + } catch (error) { + return { error: `Couldn't read the docs response: ${(error as Error).message}` }; + } let payload: any;internal-packages/dashboard-agent/src/tools.ts-872-883 (1)
872-883: 🚀 Performance & Scalability | 🟡 Minor | ⚡ Quick win
list_errorsdoesn't clampperiod, unlikelist_runsandlist_deploys.Lines 845 and 1096 both run the model-supplied
periodthroughclampPeriod; Line 877 forwards it raw. Unless the errors route clamps server-side, the model can request an unbounded window here.♻️ Proposed fix
execute: async ({ status, taskIdentifier, search, period, limit }) => { + const effectivePeriod = period ? clampPeriod(period) : undefined; const sp = new URLSearchParams(); if (status) sp.append("filter[status]", status); if (taskIdentifier) sp.append("filter[taskIdentifier]", taskIdentifier); if (search) sp.append("filter[search]", search); - if (period) sp.append("filter[period]", period); + if (effectivePeriod) sp.append("filter[period]", effectivePeriod);apps/webapp/app/routes/api.v1.queues.$queueParam.metrics.ts-72-78 (1)
72-78: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winRounding
endMsup withMath.ceilincludes future time in the averaged window.Because
endMsis rounded up to the next bucket boundary, it can be ahead ofDate.now()by up tobucketSeconds(as much as ~1/12 of the requested period).startedPerMinand other rate fields then divide the real (bounded) count by a window that partly hasn't happened yet, systematically under-reporting throughput/rate by the same proportion.Math.floorgives identical cache-alignment benefits without ever querying/averaging over future time.🐛 Proposed fix
- const endMs = Math.ceil(Date.now() / (bucketSeconds * 1000)) * bucketSeconds * 1000; + const endMs = Math.floor(Date.now() / (bucketSeconds * 1000)) * bucketSeconds * 1000;Also applies to: 124-126
🧹 Nitpick comments (32)
apps/webapp/app/components/dashboard-agent/demo/components/DemoChartCard.tsx (1)
12-30: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winDuplicate chart-card frame markup — parameterize
rowsinstead of reimplementing the frame for the empty state.
DemoChartCardhardcodesrows={demoChart.rows}with no way to override it, so the gallery's empty-chart state had to copy the entire border/title-strip/height JSX just to passrows={[]}.
apps/webapp/app/components/dashboard-agent/demo/components/DemoChartCard.tsx#L12-L30: accept an optionalrowsprop (defaulting todemoChart.rows) so callers can override the dataset.apps/webapp/app/routes/storybook.agent-ui/route.tsx#L300-L317: replaceEmptyChartCard's duplicated JSX with<DemoChartCard rows={[]} />(or equivalent) once the prop exists.apps/webapp/app/routes/storybook.agent-ui/route.tsx (1)
397-436: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winConsider deriving
untrustworthyReportvia the real stale-guard function rather than hand-rolling its output shape.The comment above this block states it's "Derived exactly the way
applyStaleGuarddoes it," but the code manually reconstructs the transformation instead of calling that function. IfapplyStaleGuard(or equivalent) is exported and importable here, calling it directly would guarantee this fixture never drifts from the real stale-telemetry behavior it's meant to demonstrate.Please confirm whether the health report's stale-guard transformation (referenced as
applyStaleGuard) is exported in a form importable from this route (e.g. fromapps/webapp/app/presenters/v3/reports/health/health.ts), so this fixture could call it directly instead of duplicating its logic.apps/webapp/app/components/dashboard-agent/demo/demo.test.ts (1)
34-39: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winThe isolation guard misses side-effect and dynamic imports.
importSpecifiersonly matches… from "x", soimport "~/foo.server"andawait import("~/db.server")slip through the very check on lines 369-378 that exists to catch them.♻️ Broaden the specifier scan
-/** Every import specifier in a file, from both `import` and `export … from`. */ +/** Every module specifier in a file: `from "x"`, `import "x"` and `import("x")`. */ function importSpecifiers(source: string): string[] { - return [...source.matchAll(/(?:import|export)[\s\S]*?from\s+["']([^"']+)["']/g)].map( - (match) => match[1]! - ); + return [ + ...source.matchAll(/from\s+["']([^"']+)["']/g), + ...source.matchAll(/\bimport\s*\(\s*["']([^"']+)["']/g), + ...source.matchAll(/\bimport\s+["']([^"']+)["']/g), + ].map((match) => match[1]!); }apps/webapp/seed-agent-examples-chats.mts (1)
257-257: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick winImport
VIEW_BLOCK_VERSIONinstead of hardcodingversion: 1.The demo fixtures stamp the envelope from the contracts constant; these seeded blocks hardcode
1. If the contract version is bumped, the strict envelope schema rejects these blocks and the cards silently degrade to plain tool rows — exactly the failure mode the transcripts exist to demonstrate. The package is already imported on line 29.♻️ Use the contract constant
-import { formatTriggerUri } from "`@internal/dashboard-agent-contracts`"; +import { formatTriggerUri, VIEW_BLOCK_VERSION } from "`@internal/dashboard-agent-contracts`";- const diagnosisEnvelope = { id: `diag_${w.failedRunId}`, version: 1 }; + const diagnosisEnvelope = { id: `diag_${w.failedRunId}`, version: VIEW_BLOCK_VERSION };const failuresChart = { id: "chart_failures_by_task", revision: 0, - version: 1, + version: VIEW_BLOCK_VERSION,const pendingChart = { id: "chart_pending_runs", revision: 0, - version: 1, + version: VIEW_BLOCK_VERSION,Also applies to: 332-362
apps/webapp/test/seedAgentExamplesChats.test.ts (1)
176-178: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winRead the kind with the contracts parser rather than
split("/")[4].Positional indexing silently mis-classifies if the URI layout changes — a
runURI read asreportwould skip the resolution assertion entirely, and the test would still pass.demo.test.tsusessafeParseTriggerUrifor exactly this.♻️ Parse instead of index
for (const uri of uris) { - const kind = uri.split("/")[4]; - if (UNRESOLVABLE_KINDS.includes(kind)) continue; + const parsed = safeParseTriggerUri(uri); + expect(parsed.success, uri).toBe(true); + if (!parsed.success || UNRESOLVABLE_KINDS.includes(parsed.data.kind)) continue; const resolved = resolveTriggerUri(SCOPE, uri);Add the import:
import { safeParseTriggerUri } from "`@internal/dashboard-agent-contracts`";internal-packages/dashboard-agent-contracts/src/trigger-uri.ts (1)
320-341: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low valueDuplicate
lineparams are silently accepted, last one wins.
trigger://…/source/abc/a.ts?line=1&line=2parses asline: 2. Everything else in the grammar rejects non-canonical input (fragments, unknown params, empty segments), so accepting a duplicate here is inconsistent and lets two different URIs mean the same resource.♻️ Reject duplicates
for (const [key, value] of params) { if (key !== "line") { return { success: false, error: `unknown query param "${key}"` }; } + if (line !== undefined) { + return { success: false, error: "duplicate query param \"line\"" }; + } + if (!/^\d+$/.test(value) || Number(value) < 1) {internal-packages/dashboard-agent/src/watch-tick.ts (1)
212-224: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value
wakeActioninfers the action type from "not fired".If
isTerminalWatchStatusever admits a third terminal status (e.g.cancelled, which the contract'swatchStatusSchemaincludes), the delivery-only path producestype: "watch.expired"withid: watch:<id>:cancelled— a type/id pair that doesn't describe what happened. Switching on the status explicitly keeps that from slipping through silently.♻️ Switch on the status
function wakeAction(watch: Watch, facts: Record<string, unknown>): WatchWakeAction { const spec = watch.spec as PersistedWatchSpec; + if (watch.status !== "fired" && watch.status !== "expired") { + throw new Error(`cannot build a wake for a ${watch.status} watch`); + } return { - type: watch.status === "fired" ? "watch.fired" : "watch.expired", + type: watch.status === "fired" ? "watch.fired" : "watch.expired",internal-packages/dashboard-agent/src/dashboard-agent.eval.ts (1)
582-585: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueUse
APICallError.isInstance(error)for provider error detection.
error.name.includes("APICallError")depends on the error name surviving any wrapping or renaming; the SDK’s provided type guard is more reliable.♻️ Use the SDK's type guard
- const infra = error instanceof Error && error.name.includes("APICallError"); + const infra = APICallError.isInstance(error);plus
import { APICallError } from "ai";internal-packages/dashboard-agent/src/dashboard-agent.test.ts (1)
429-432: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winPoll the eval-enqueue side effect instead of relying on a fixed sleep.
turnAtRatewaits only 30 ms before returning calls, which can still fail when the runner is loaded. Move the assertion out of the helper and make it wait for the expected call count, e.g.vi.waitFor(() => expect(calls).toHaveLength(1), { timeout: 2000 }); for the rate-0 path keep a bounded wait on “still empty” if needed.internal-packages/dashboard-agent-contracts/src/watch.ts (1)
38-61: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winConsider
z.discriminatedUnion("kind", [...])instead ofz.union.All five branches share a literal
kinddiscriminator, so this is a textbook case forz.discriminatedUnion. With plainz.union, an invalid payload (e.g., wrongkindor a badrunId) produces a combinedinvalid_unionerror listing every failed branch, which is noisier to surface back to the agent/tool-caller than the targeted errordiscriminatedUniongives.♻️ Proposed refactor
-export const watchSpecSchema = z.union([ +export const watchSpecSchema = z.discriminatedUnion("kind", [ watchCommonSchema .extend({ kind: z.literal("run_start"), runId: z.string() }) .merge(runStateCadenceSchema),internal-packages/dashboard-agent-db/src/queries.ts (1)
684-698: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winExtract the shared unread-wake predicate.
The same
(last_read_at is null or coalesce(fired_at, last_checked_at) > last_read_at)clause plus thestatus in ('fired','expired')+ tenancy join is repeated verbatim incountUnreadWatchWakes,listUnreadWatchWakes(Line 744), andlistChatIdsWithUnreadWakes(Line 783). One helper returning theand(...)condition keeps the wake definition single-sourced — the doc comments already assert all three share it.♻️ Sketch
+function unreadWakeCondition(params: { organizationId: string; userId: string }) { + return and( + inArray(watches.status, ["fired", "expired"]), + eq(chats.organizationId, params.organizationId), + eq(chats.userId, params.userId), + isNull(chats.deletedAt), + sql`(${chats.lastReadAt} is null or coalesce(${watches.firedAt}, ${watches.lastCheckedAt}) > ${chats.lastReadAt})` + ); +}internal-packages/dashboard-agent/VERDICTS.md (1)
104-108: 📐 Maintainability & Code Quality | 🔵 TrivialTrack the documented
queuedDurationbug.
RunPresenter.server.tscomputingqueuedDurationasstartedAt − createdAtis recorded here as knowingly unfixed, which over-reports for delayed/scheduled runs in the dashboard. Want me to open an issue so it doesn't only live in this markdown file?internal-packages/dashboard-agent/src/dashboard-agent.ts (1)
622-626: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueUse the same non-null assertion as
withCacheBreakpointOnLast.
sanitized[sanitized.length - 1]is typedModelMessage | undefinedundernoUncheckedIndexedAccess, and it's then spread at Line 628. The helper at Line 378 already handles this with!; mirror it here so the two paths type-check identically.♻️ Proposed tweak
- const last = sanitized[sanitized.length - 1]; + const last = sanitized[sanitized.length - 1]!;internal-packages/dashboard-agent/src/tool-schemas.ts (1)
398-403: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick winValidate the alert email shape in the schema.
z.string().email()makes the model's mistake a tool-validation error it can correct in-turn.♻️ Proposed change
email: z - .string() + .string() + .email() .optional() .describe("Email to alert. Omit to use the user's own account email."),apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx (1)
92-97: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win
unknown[]+as neverthrows away the block contract.
blocksForreturnsunknown[], forcingblocks as neverat theViewBlockscall site, so a block-shape change in@internal/dashboard-agent-contractswon't surface at compile time here. Typing the return as the catalog's block union would keep the boundary checked.Also applies to: 222-228
apps/webapp/app/components/dashboard-agent/DashboardAgentPanel.tsx (1)
471-476: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low value
?? []hands a new array down on every render.
chatWatchesgets a fresh identity each render, which flows intoDashboardAgentChat→DashboardAgentMessagesand defeats thememoonDashboardAgentTurn(itswatchesprop always compares unequal). A module-levelconst NO_WATCHES: WatchChip[] = []fallback keeps the reference stable.apps/webapp/app/components/dashboard-agent/DashboardAgentSuggestedPrompts.tsx (1)
58-65: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueName the "no page context" fallback.
The inline
{ page: { kind: "other", path: "" }, signals: [] }is a placeholder context built at the call site; a shared named constant (e.g.UNKNOWN_PAGE_CONTEXTinsuggested-prompts/registry.ts) keeps the meaning of the emptypathexplicit and reusable.As per coding guidelines: "Use named constants for sentinel or placeholder values instead of scattering raw string literals across comparisons."
Source: Coding guidelines
apps/webapp/app/components/dashboard-agent/suggested-prompts/registry.ts (1)
217-222: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win
SIGNAL_PRIORITYisn't exhaustiveness-checked, and the two iterators duplicate one loop.
SIGNAL_SLOTis aRecord<AgentPageSignalKind, …>, so a new signal kind fails to compile there — butSIGNAL_PRIORITYis a bare array, and since both iterators drive off it, a kind missing from the array silently never produces a chip.contextualPromptsis alsocontextualPromptsBySlotflattened in slot order.♻️ Make the priority list exhaustive and derive the flat list
-export const SIGNAL_PRIORITY: AgentPageSignalKind[] = [ +// A tuple typed against the kind union: omitting a new kind is a compile error. +export const SIGNAL_PRIORITY = [ "fresh_failure", "waiting_run", "slow_run", "concurrency_saturation", -]; +] as const satisfies readonly AgentPageSignalKind[];export function contextualPrompts(context: AgentPageContext, now: number): SuggestedPrompt[] { - const prompts: SuggestedPrompt[] = []; - for (const kind of SIGNAL_PRIORITY) { - for (const signal of context.signals) { - if (signal.kind !== kind) continue; - const prompt = promptForSignal(signal, now); - if (prompt) prompts.push(prompt); - } - } - return prompts; + const bySlot = contextualPromptsBySlot(context, now); + return PROMPT_SLOTS.flatMap((slot) => bySlot[slot]); }Note: this changes
contextualPromptsordering from signal-priority to slot order — keep the current loop if callers depend on the former.Also applies to: 284-320
apps/webapp/app/components/dashboard-agent/ReportView.tsx (1)
37-39: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueComment describes a registration side effect that doesn't exist.
healthMessagesis used purely as a value in the staticCATALOGSmap on Line 89 — nothing self-registers on import. Worth correcting so a future reader doesn't assume adding an import is enough to register a new report's catalog.apps/webapp/app/components/dashboard-agent/agent-badges.tsx (1)
46-46: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winHand-rolled icon component signature duplicated across two files. Both files type heroicons components as a bare call signature returning
JSX.Element, which is version-sensitive (ForwardRefExoticComponent's call signature returnsReactNode) and duplicated rather than shared.
apps/webapp/app/components/dashboard-agent/agent-badges.tsx#L46-L46: change the exportedIconComponentalias toReact.ComponentType<{ className?: string }>.apps/webapp/app/components/dashboard-agent/WakeBanner.tsx#L77-L82: importIconComponentfrom./agent-badgesand typeTONE_ICONasRecord<AgentTone, IconComponent>instead of restating the signature inline.apps/webapp/app/components/dashboard-agent/suggested-prompts/dismissal.ts (1)
28-35: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueDismissals are permanent and the key set is never pruned.
Every dismissed id leaves a key behind forever, including operator-controlled promoted-prompt ids that rotate. Consider storing a timestamp instead of
"1"so stale entries can expire (and a chip can come back after a while), or prune on read.apps/webapp/app/components/dashboard-agent/suggested-prompts/page-mappers.test.ts (1)
192-195: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueTest name contradicts its fixture.
running: 10against aconcurrencyLimitof 10 is at the limit, not "idle under its limit" — the case being covered is "at capacity with an empty queue". Renaming keeps the boundary this test pins obvious.apps/webapp/app/components/dashboard-agent/suggested-prompts/resolver.test.ts (1)
164-172: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value
toContain("")passes vacuously if the fixture changes kind.Line 223 in this same file already uses the stronger pattern (
throw new Error("fixture changed")); the ternary here silently degrades to an assertion that can never fail. Prefer the narrowing guard for consistency.♻️ Proposed change
it("sends the full prompt text, not the short label", () => { const [failure] = resolveSuggestedPrompts(demoPageContexts.failedRun, { now: NOW }); + const page = demoPageContexts.failedRun.page; + if (page.kind !== "run") throw new Error("fixture changed"); expect(failure?.label).toBe("Why did this run fail?"); - expect(failure?.prompt).toContain( - demoPageContexts.failedRun.page.kind === "run" ? demoPageContexts.failedRun.page.runId : "" - ); + expect(failure?.prompt).toContain(page.runId); expect(failure?.prompt).toContain("12m ago"); });internal-packages/dashboard-agent/src/tools.ts (3)
596-624: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueMisplaced doc block: the
renderInvestigationsdocs sit oncanonicalizeEvidence.Two doc comments are stacked here; the first (Lines 596-613, describing block stamping and
continueId) documentsrenderInvestigations, which is declared at Line 706. Move it there so tooling and readers attach it correctly.
722-779: 🗄️ Data Integrity & Integration | 🔵 Trivial | 💤 Low valueTwo
investigationblocks in one view collapse into one row.
currentInvestigationIdis assigned from the first block's upsert, so a secondinvestigationblock in the samerender_viewcall revises the first rather than creating a second investigation — both blocks then carry the same id with different revisions. If the schema permits multiple investigation blocks per view, consider rejecting that up front (or scoping the id per block) rather than silently merging.
1078-1089: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueComment says "double-encode" but the code encodes once.
Line 1081 applies
encodeURIComponenta single time (task/my-task→task%2Fmy-task), which is what the route's un-escaping expects. Reword the comment. Also worth noting: unlike the neighbouring tools, this returnsresult.dataverbatim, so any series/histogram fields in the metrics payload land straight in the model's context — consider acurateQueuein line withcurateReport.apps/webapp/app/routes/api.v1.projects.$projectRef.$env.runs.$runId.commit.ts (1)
27-37: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick winParse the
gitJSON blob with zod instead of a bare cast.
deployment.gitis untyped Prisma JSON; the cast asserts a shape that is never checked, so a legacy/oddly-shaped blob would flow straight into the API response (e.g.pullRequestNumberas a string). A smallz.object({...}).partial().safeParse()keeps the response contract honest.As per coding guidelines: "Use zod for validation in packages/core and apps/webapp".
♻️ Proposed refactor
-type GitMetaBlob = { - source?: string; - commitAuthorName?: string; - commitMessage?: string; - commitRef?: string; - remoteUrl?: string; - ghUsername?: string; - pullRequestNumber?: number; - pullRequestTitle?: string; - pullRequestState?: string; -}; +const GitMetaBlob = z + .object({ + source: z.string(), + commitAuthorName: z.string(), + commitMessage: z.string(), + commitRef: z.string(), + remoteUrl: z.string(), + ghUsername: z.string(), + pullRequestNumber: z.number(), + pullRequestTitle: z.string(), + pullRequestState: z.string(), + }) + .partial();- const git = (deployment?.git ?? undefined) as GitMetaBlob | undefined; + const parsedGit = deployment?.git ? GitMetaBlob.safeParse(deployment.git) : undefined; + const git = parsedGit?.success ? parsedGit.data : undefined;Also applies to: 73-73
Source: Coding guidelines
apps/webapp/app/routes/api.v1.dashboard-agent.alerts.ts (1)
156-159: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winMap
ServiceValidationErrorfromCreateAlertChannelService.callto a 4xx response.The catch block currently treats all
CreateAlertChannelService.callfailures as 500, including user-input validation failures such as alert-channel limits. DistinguishServiceValidationErrorhere and return a 4xx, so the agent can explain the fixable failure instead of seeing an internal error.apps/webapp/test/dashboardAgentRoutes.test.ts (1)
26-29: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueDead mock.
vi.mock("~/env.server")just re-exports the original module, so it has no effect — either drop it or note why the module factory is needed (e.g. to force ESM interop ordering).apps/webapp/test/dashboardAgentWatchToken.test.ts (1)
15-15: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueHardcoded UAT prefix can drift.
WATCH_TOKEN_PREFIXis imported buttr_uat_is literal; if the rbac package ever changes its prefix, the "disguised" tokens in the cross-rejection tests stop testing what they claim while still passing. Export/import the constant from@trigger.dev/rbacif available.apps/webapp/test/dashboardAgentWatches.test.ts (1)
371-375: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueConditional assertion can pass vacuously. If
second.okwere unexpectedly true theexistingIdcheck is skipped silently. Narrow with an earlyif (second.ok || !first.ok) throw new Error(...)(orexpect.fail) before asserting.apps/webapp/app/v3/services/alerts/deliverDashboardAgentWatchAlert.server.ts (1)
411-417: 🩺 Stability & Availability | 🔵 Trivial | 💤 Low valueGuard the cast before reading
.code. Both predicates dereference anunknownvalue; a thrownnull/undefined(or a primitive) turns thecatchblock itself into aTypeError, losing the original failure. Atypeof error === "object" && error !== nullprefix makes them safe.🛡️ Proposed guard
function isWebAPIPlatformError(error: unknown): error is WebAPIPlatformError { - return (error as WebAPIPlatformError).code === ErrorCode.PlatformError; + return ( + typeof error === "object" && + error !== null && + (error as WebAPIPlatformError).code === ErrorCode.PlatformError + ); } function isWebAPIRateLimitedError(error: unknown): error is WebAPIRateLimitedError { - return (error as WebAPIRateLimitedError).code === ErrorCode.RateLimitedError; + return ( + typeof error === "object" && + error !== null && + (error as WebAPIRateLimitedError).code === ErrorCode.RateLimitedError + ); }
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 32f81d27-7b23-4a54-8b29-c8916991756f
⛔ Files ignored due to path filters (1)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (209)
.server-changes/dashboard-agent-first-turn-error.md.server-changes/dashboard-agent-investigate.md.server-changes/dashboard-agent-watch-alerts.md.server-changes/dashboard-agent-watches.md.server-changes/queue-metrics-api.md.server-changes/remove-header-docs-buttons.mdapps/webapp/.gitignoreapps/webapp/app/components/dashboard-agent/AgentChart.tsxapps/webapp/app/components/dashboard-agent/DashboardAgent.tsxapps/webapp/app/components/dashboard-agent/DashboardAgentChat.tsxapps/webapp/app/components/dashboard-agent/DashboardAgentComposer.tsxapps/webapp/app/components/dashboard-agent/DashboardAgentContextBanner.tsxapps/webapp/app/components/dashboard-agent/DashboardAgentDraft.tsxapps/webapp/app/components/dashboard-agent/DashboardAgentHeader.tsxapps/webapp/app/components/dashboard-agent/DashboardAgentHistory.tsxapps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsxapps/webapp/app/components/dashboard-agent/DashboardAgentPanel.tsxapps/webapp/app/components/dashboard-agent/DashboardAgentSuggestedPrompts.tsxapps/webapp/app/components/dashboard-agent/InvestigateButton.tsxapps/webapp/app/components/dashboard-agent/InvestigationCard.test.tsapps/webapp/app/components/dashboard-agent/InvestigationCard.tsxapps/webapp/app/components/dashboard-agent/ReportView.test.tsapps/webapp/app/components/dashboard-agent/ReportView.tsxapps/webapp/app/components/dashboard-agent/RunDiagnosisCard.tsxapps/webapp/app/components/dashboard-agent/WakeBanner.tsxapps/webapp/app/components/dashboard-agent/WatchChips.tsxapps/webapp/app/components/dashboard-agent/WatchWakeToast.tsxapps/webapp/app/components/dashboard-agent/agent-badges.tsxapps/webapp/app/components/dashboard-agent/chat-layout.test.tsapps/webapp/app/components/dashboard-agent/chat-layout.tsxapps/webapp/app/components/dashboard-agent/dashboardAgentLauncher.tsxapps/webapp/app/components/dashboard-agent/demo/components/DemoChartCard.tsxapps/webapp/app/components/dashboard-agent/demo/components/DemoIntentBubble.tsxapps/webapp/app/components/dashboard-agent/demo/components/DemoInvestigationCard.tsxapps/webapp/app/components/dashboard-agent/demo/components/DemoReportCard.tsxapps/webapp/app/components/dashboard-agent/demo/components/DemoSuggestedPromptsRow.tsxapps/webapp/app/components/dashboard-agent/demo/components/DemoWatchChips.tsxapps/webapp/app/components/dashboard-agent/demo/demo-chats.tsapps/webapp/app/components/dashboard-agent/demo/demo.test.tsapps/webapp/app/components/dashboard-agent/demo/fixtures/blocks.tsapps/webapp/app/components/dashboard-agent/demo/fixtures/chart.tsapps/webapp/app/components/dashboard-agent/demo/fixtures/index.tsapps/webapp/app/components/dashboard-agent/demo/fixtures/intents.tsapps/webapp/app/components/dashboard-agent/demo/fixtures/investigation.tsapps/webapp/app/components/dashboard-agent/demo/fixtures/messages.tsapps/webapp/app/components/dashboard-agent/demo/fixtures/page-context.tsapps/webapp/app/components/dashboard-agent/demo/fixtures/reports.tsapps/webapp/app/components/dashboard-agent/demo/fixtures/watches.tsapps/webapp/app/components/dashboard-agent/demo/ids.tsapps/webapp/app/components/dashboard-agent/demo/index.tsapps/webapp/app/components/dashboard-agent/investigate-prompts.test.tsapps/webapp/app/components/dashboard-agent/investigate-prompts.tsapps/webapp/app/components/dashboard-agent/list-row.tsxapps/webapp/app/components/dashboard-agent/message-order.test.tsapps/webapp/app/components/dashboard-agent/message-order.tsapps/webapp/app/components/dashboard-agent/navigate-target.test.tsapps/webapp/app/components/dashboard-agent/navigate-target.tsapps/webapp/app/components/dashboard-agent/page-context-types.tsapps/webapp/app/components/dashboard-agent/page-label.test.tsapps/webapp/app/components/dashboard-agent/page-label.tsapps/webapp/app/components/dashboard-agent/progress-line.test.tsapps/webapp/app/components/dashboard-agent/progress-line.tsapps/webapp/app/components/dashboard-agent/report-block-adapter.test.tsapps/webapp/app/components/dashboard-agent/report-block-adapter.tsapps/webapp/app/components/dashboard-agent/report-sparkline.tsxapps/webapp/app/components/dashboard-agent/run-id.test.tsapps/webapp/app/components/dashboard-agent/run-id.tsapps/webapp/app/components/dashboard-agent/suggested-prompts/dismissal.tsapps/webapp/app/components/dashboard-agent/suggested-prompts/index.tsapps/webapp/app/components/dashboard-agent/suggested-prompts/page-mappers.test.tsapps/webapp/app/components/dashboard-agent/suggested-prompts/page-mappers.tsapps/webapp/app/components/dashboard-agent/suggested-prompts/promoted.test.tsapps/webapp/app/components/dashboard-agent/suggested-prompts/promoted.tsapps/webapp/app/components/dashboard-agent/suggested-prompts/promotedPrompt.server.tsapps/webapp/app/components/dashboard-agent/suggested-prompts/registry.tsapps/webapp/app/components/dashboard-agent/suggested-prompts/resolver.test.tsapps/webapp/app/components/dashboard-agent/suggested-prompts/resolver.tsapps/webapp/app/components/dashboard-agent/tool-labels.test.tsapps/webapp/app/components/dashboard-agent/tool-labels.tsapps/webapp/app/components/dashboard-agent/useTranscriptAutoScroll.tsapps/webapp/app/components/dashboard-agent/view-blocks.test.tsapps/webapp/app/components/dashboard-agent/view-blocks.tsapps/webapp/app/components/dashboard-agent/view-catalog.tsxapps/webapp/app/components/dashboard-agent/watch-chips.test.tsapps/webapp/app/components/dashboard-agent/watch-chips.tsapps/webapp/app/components/metrics/MiniLineChart.tsxapps/webapp/app/components/primitives/Callout.tsxapps/webapp/app/components/runs/v3/agent/AgentMessageView.tsxapps/webapp/app/hooks/useAgentPageContext.tsapps/webapp/app/presenters/v3/ApiAlertChannelPresenter.server.tsapps/webapp/app/presenters/v3/reports/health/health-messages.tsapps/webapp/app/presenters/v3/reports/health/health.tsapps/webapp/app/presenters/v3/waitingRun/waitingRunDiagnosis.server.tsapps/webapp/app/presenters/v3/waitingRun/waitingRunDiagnosis.tsapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam._index/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.agents.$agentParam/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.alerts.new/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.alerts/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.apikeys/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.batches/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.branches/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.bulk-actions/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.deployments/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.dev-branches/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.environment-variables/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.errors.$fingerprint/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.limits/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.prompts._index/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.runs.$runParam/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.runs._index/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.sessions.$sessionParam/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.sessions._index/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.test/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.waitpoints.tokens/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.settings.private-connections._index/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.settings.private-connections.new/route.tsxapps/webapp/app/routes/account.tokens/route.tsxapps/webapp/app/routes/api.v1.dashboard-agent.alerts.$channelId.tsapps/webapp/app/routes/api.v1.dashboard-agent.alerts.tsapps/webapp/app/routes/api.v1.dashboard-agent.watches.$watchId.check.tsapps/webapp/app/routes/api.v1.dashboard-agent.watches.$watchId.fired.tsapps/webapp/app/routes/api.v1.dashboard-agent.watches.tsapps/webapp/app/routes/api.v1.projects.$projectRef.$env.jwt.tsapps/webapp/app/routes/api.v1.projects.$projectRef.$env.repo.snapshot.tsapps/webapp/app/routes/api.v1.projects.$projectRef.$env.runs.$runId.commit.tsapps/webapp/app/routes/api.v1.projects.$projectRef.$env.runs.$runId.waiting.tsapps/webapp/app/routes/api.v1.projects.$projectRef.$env.workers.$tagName.tsapps/webapp/app/routes/api.v1.queues.$queueParam.metrics.tsapps/webapp/app/routes/resources.dashboard-agent.alerts.$channelId.unsubscribe.tsxapps/webapp/app/routes/resources.orgs.$organizationSlug.projects.$projectParam.env.$envParam.dashboard-agent.in.$.tsapps/webapp/app/routes/resources.orgs.$organizationSlug.projects.$projectParam.env.$envParam.dashboard-agent.tsapps/webapp/app/routes/storybook.agent-ui/manifest.tsapps/webapp/app/routes/storybook.agent-ui/route.tsxapps/webapp/app/routes/storybook.callout/route.tsxapps/webapp/app/services/dashboardAgentAlertContext.server.tsapps/webapp/app/services/dashboardAgentAlertUnsubscribeToken.server.tsapps/webapp/app/services/dashboardAgentHeadStart.server.tsapps/webapp/app/services/dashboardAgentWatchAlerts.server.tsapps/webapp/app/services/dashboardAgentWatchChecks.server.tsapps/webapp/app/services/dashboardAgentWatchChecks.tsapps/webapp/app/services/dashboardAgentWatchToken.server.tsapps/webapp/app/services/dashboardAgentWatches.server.tsapps/webapp/app/services/resolveTriggerUri.server.tsapps/webapp/app/services/uatRoutePreamble.server.tsapps/webapp/app/utils/handle.tsapps/webapp/app/v3/alertsWorker.server.tsapps/webapp/app/v3/featureFlags.tsapps/webapp/app/v3/services/alerts/deliverAlert.server.tsapps/webapp/app/v3/services/alerts/deliverDashboardAgentWatchAlert.server.tsapps/webapp/package.jsonapps/webapp/scripts/agent-ui-screenshots.tsapps/webapp/seed-agent-examples-chats.mtsapps/webapp/seed-agent-examples.mtsapps/webapp/seed-queue-metrics.mtsapps/webapp/test/dashboardAgentHeadStart.test.tsapps/webapp/test/dashboardAgentRoutes.test.tsapps/webapp/test/dashboardAgentWatchChecks.test.tsapps/webapp/test/dashboardAgentWatchToken.test.tsapps/webapp/test/dashboardAgentWatches.test.tsapps/webapp/test/reportHealth.test.tsapps/webapp/test/resolveTriggerUri.test.tsapps/webapp/test/seedAgentExamplesChats.test.tsapps/webapp/test/waitingRunDiagnosis.test.tsapps/webapp/vitest.config.tsinternal-packages/dashboard-agent-contracts/package.jsoninternal-packages/dashboard-agent-contracts/src/blocks.test.tsinternal-packages/dashboard-agent-contracts/src/blocks.tsinternal-packages/dashboard-agent-contracts/src/contracts.test.tsinternal-packages/dashboard-agent-contracts/src/evidence.tsinternal-packages/dashboard-agent-contracts/src/index.tsinternal-packages/dashboard-agent-contracts/src/intent.tsinternal-packages/dashboard-agent-contracts/src/page-context.tsinternal-packages/dashboard-agent-contracts/src/run-filters.tsinternal-packages/dashboard-agent-contracts/src/suggested-prompts.tsinternal-packages/dashboard-agent-contracts/src/trigger-uri.test.tsinternal-packages/dashboard-agent-contracts/src/trigger-uri.tsinternal-packages/dashboard-agent-contracts/src/watch.test.tsinternal-packages/dashboard-agent-contracts/src/watch.tsinternal-packages/dashboard-agent-contracts/tsconfig.jsoninternal-packages/dashboard-agent-contracts/vitest.config.tsinternal-packages/dashboard-agent-db/README.mdinternal-packages/dashboard-agent-db/drizzle/0002_luxuriant_king_cobra.sqlinternal-packages/dashboard-agent-db/drizzle/0003_famous_champions.sqlinternal-packages/dashboard-agent-db/drizzle/meta/0002_snapshot.jsoninternal-packages/dashboard-agent-db/drizzle/meta/0003_snapshot.jsoninternal-packages/dashboard-agent-db/drizzle/meta/_journal.jsoninternal-packages/dashboard-agent-db/package.jsoninternal-packages/dashboard-agent-db/src/ids.tsinternal-packages/dashboard-agent-db/src/index.tsinternal-packages/dashboard-agent-db/src/queries.tsinternal-packages/dashboard-agent-db/src/schema.tsinternal-packages/dashboard-agent/GUIDEBOOK.mdinternal-packages/dashboard-agent/PLAYBOOK.mdinternal-packages/dashboard-agent/VERDICTS.mdinternal-packages/dashboard-agent/package.jsoninternal-packages/dashboard-agent/src/dashboard-agent.eval.tsinternal-packages/dashboard-agent/src/dashboard-agent.test.tsinternal-packages/dashboard-agent/src/dashboard-agent.tsinternal-packages/dashboard-agent/src/index.tsinternal-packages/dashboard-agent/src/tool-schemas.tsinternal-packages/dashboard-agent/src/tools.tsinternal-packages/dashboard-agent/src/watch-tick.test.tsinternal-packages/dashboard-agent/src/watch-tick.tsinternal-packages/dashboard-agent/vitest.eval.config.tsinternal-packages/database/prisma/migrations/20260729120000_add_dashboard_agent_watch_alert_type/migration.sqlinternal-packages/database/prisma/schema.prismainternal-packages/emails/emails/alert-dashboard-agent-watch.tsxinternal-packages/emails/src/index.tsx
💤 Files with no reviewable changes (1)
- apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.branches/route.tsx
| <SimpleTooltip | ||
| side="bottom" | ||
| content={watchChipTooltip(watch)} | ||
| button={<span className="max-w-[12rem] truncate">{label}</span>} | ||
| /> |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win
The note/cadence tooltip is mouse-only.
The chip's trigger is a plain <span>, so keyboard and screen-reader users never reach the tooltip — and per the comment on Lines 70-72 the native title was deliberately dropped, making this the only path to the note and cadence. SimpleTooltip already supports tabbable (used for the cancel button on Line 84); apply it here too.
♿ Proposed fix
<SimpleTooltip
+ tabbable
side="bottom"
content={watchChipTooltip(watch)}
button={<span className="max-w-[12rem] truncate">{label}</span>}
/>📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| <SimpleTooltip | |
| side="bottom" | |
| content={watchChipTooltip(watch)} | |
| button={<span className="max-w-[12rem] truncate">{label}</span>} | |
| /> | |
| <SimpleTooltip | |
| tabbable | |
| side="bottom" | |
| content={watchChipTooltip(watch)} | |
| button={<span className="max-w-[12rem] truncate">{label}</span>} | |
| /> |
| export function showWatchWakesSummaryToast(count: number, onOpenChat: () => void) { | ||
| show( | ||
| (t) => ( | ||
| <WakeToastUI | ||
| t={t} | ||
| title="Watch updates" | ||
| message={`${count} watch updates — open the chat panel.`} | ||
| onOpenChat={onOpenChat} | ||
| /> | ||
| ), | ||
| `watch-wakes-summary-${count}-${Date.now()}` | ||
| ); | ||
| } |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Date.now() in the toast id defeats the de-duplication this helper exists for.
Every call produces a unique id, so a repeated poll stacks another summary toast — and these never auto-dismiss (duration: Infinity), so they accumulate until the user clears each one. Use a stable id for the summary toast; sonner will update the existing one when the count changes.
🐛 Proposed fix
- `watch-wakes-summary-${count}-${Date.now()}`
+ "watch-wakes-summary"📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| export function showWatchWakesSummaryToast(count: number, onOpenChat: () => void) { | |
| show( | |
| (t) => ( | |
| <WakeToastUI | |
| t={t} | |
| title="Watch updates" | |
| message={`${count} watch updates — open the chat panel.`} | |
| onOpenChat={onOpenChat} | |
| /> | |
| ), | |
| `watch-wakes-summary-${count}-${Date.now()}` | |
| ); | |
| } | |
| export function showWatchWakesSummaryToast(count: number, onOpenChat: () => void) { | |
| show( | |
| (t) => ( | |
| <WakeToastUI | |
| t={t} | |
| title="Watch updates" | |
| message={`${count} watch updates — open the chat panel.`} | |
| onOpenChat={onOpenChat} | |
| /> | |
| ), | |
| "watch-wakes-summary" | |
| ); | |
| } |
| function deriveCause( | ||
| queue: WaitingRunDiagnosis["queue"], | ||
| signals: WaitingRunQueueSignals | null | ||
| ): { cause: WaitingRunCause; evidence: WaitingRunDiagnosis["diagnosis"]["evidence"] } { | ||
| const t = HEALTH_THRESHOLDS.flowCause; | ||
|
|
||
| if (!signals || queue.sampleBuckets === 0) { | ||
| return { | ||
| cause: "unknown", | ||
| evidence: { | ||
| backlogGrowing: false, | ||
| throttledShare: queue.throttled.share, | ||
| envRunningShare: null, | ||
| missing: "queue_signals", | ||
| }, | ||
| }; | ||
| } | ||
|
|
||
| const backlogGrowing = isPendingIncreasing(signals.depthSeries); | ||
| const throttledShare = queue.throttled.share; | ||
| // Same guard as flow.ts #1: without a real limit AND a real running reading, a share is a | ||
| // meaningless 0 that would falsely select `stall`. | ||
| const hasConcurrencyEvidence = | ||
| signals.envLimit !== null && signals.envLimit > 0 && signals.envRunning !== null; | ||
| const envRunningShare = hasConcurrencyEvidence | ||
| ? (signals.envRunning as number) / (signals.envLimit as number) | ||
| : null; | ||
| const envPinned = envRunningShare !== null && envRunningShare >= t.pinnedLevel; | ||
| // A queue's own limit is visible through throttling: `throttled_count` counts exactly the | ||
| // emissions where running >= limit while work was queued. Sustained (most of the window) | ||
| // reads as pinned at the queue limit; intermittent reads as throttled. | ||
| const queueLimitPinned = throttledShare >= t.pinnedShare; | ||
| const queueThrottled = throttledShare >= t.throttledShare; | ||
| const backlogged = queue.depth !== null && queue.depth > 0; | ||
| const observedRate = queue.observedThroughputPerMin; | ||
|
|
||
| const evidence = { | ||
| backlogGrowing, | ||
| throttledShare, | ||
| envRunningShare, | ||
| missing: null as WaitingRunDiagnosis["diagnosis"]["evidence"]["missing"], | ||
| }; | ||
|
|
||
| // Priority order copied from flow.ts: stall is a last-resort "it's on our side" cause, so a | ||
| // known config bottleneck (queue throttling) must rule it out first. | ||
| if ( | ||
| hasConcurrencyEvidence && | ||
| !queueThrottled && | ||
| (envRunningShare as number) < t.stallRunningShare && | ||
| backlogged && | ||
| observedRate === 0 | ||
| ) { | ||
| return { cause: "stall", evidence }; | ||
| } | ||
| if (envPinned && backlogged) { | ||
| return { cause: "env_limit_pinned", evidence }; | ||
| } | ||
| if (queueLimitPinned && backlogged) { | ||
| return { cause: "queue_limit_pinned", evidence }; | ||
| } | ||
| if (queueThrottled && backlogged) { | ||
| return { cause: "throttled", evidence }; | ||
| } | ||
| if (!backlogged || (observedRate !== null && observedRate > 0)) { | ||
| return { cause: "draining_normally", evidence }; | ||
| } | ||
| // Backlogged with nothing moving, but no capacity evidence to say whether that's a limit or a | ||
| // stall. flow.ts's lesson: don't name a concurrency cause without the evidence for it. | ||
| return { cause: "unknown", evidence: { ...evidence, missing: "env_concurrency" } }; | ||
| } |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
missing: "env_concurrency" fallback mislabels evidence that's actually present.
The final fallback (Line 398) unconditionally reports missing: "env_concurrency", but this branch is reachable even when hasConcurrencyEvidence is true (e.g. envRunningShare between the stall and pinned thresholds, or observedRate unmeasured rather than exactly 0 — the stall check requires observedRate === 0, so a null rate never satisfies it). In those cases concurrency data isn't missing at all; the diagnosis is just inconclusive, but a consumer reading evidence.missing will be told the wrong thing is absent. This directly undercuts the module's own "never overclaim" design intent stated in the file header.
🐛 Proposed fix
// Backlogged with nothing moving, but no capacity evidence to say whether that's a limit or a
// stall. flow.ts's lesson: don't name a concurrency cause without the evidence for it.
- return { cause: "unknown", evidence: { ...evidence, missing: "env_concurrency" } };
+ return {
+ cause: "unknown",
+ evidence: { ...evidence, missing: hasConcurrencyEvidence ? null : "env_concurrency" },
+ };Consider adding a test where envRunning/envLimit are both present but the share falls between the stall and pinned thresholds (or startedCount: null) with a non-zero backlog, to lock in the correct missing value going forward.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| function deriveCause( | |
| queue: WaitingRunDiagnosis["queue"], | |
| signals: WaitingRunQueueSignals | null | |
| ): { cause: WaitingRunCause; evidence: WaitingRunDiagnosis["diagnosis"]["evidence"] } { | |
| const t = HEALTH_THRESHOLDS.flowCause; | |
| if (!signals || queue.sampleBuckets === 0) { | |
| return { | |
| cause: "unknown", | |
| evidence: { | |
| backlogGrowing: false, | |
| throttledShare: queue.throttled.share, | |
| envRunningShare: null, | |
| missing: "queue_signals", | |
| }, | |
| }; | |
| } | |
| const backlogGrowing = isPendingIncreasing(signals.depthSeries); | |
| const throttledShare = queue.throttled.share; | |
| // Same guard as flow.ts #1: without a real limit AND a real running reading, a share is a | |
| // meaningless 0 that would falsely select `stall`. | |
| const hasConcurrencyEvidence = | |
| signals.envLimit !== null && signals.envLimit > 0 && signals.envRunning !== null; | |
| const envRunningShare = hasConcurrencyEvidence | |
| ? (signals.envRunning as number) / (signals.envLimit as number) | |
| : null; | |
| const envPinned = envRunningShare !== null && envRunningShare >= t.pinnedLevel; | |
| // A queue's own limit is visible through throttling: `throttled_count` counts exactly the | |
| // emissions where running >= limit while work was queued. Sustained (most of the window) | |
| // reads as pinned at the queue limit; intermittent reads as throttled. | |
| const queueLimitPinned = throttledShare >= t.pinnedShare; | |
| const queueThrottled = throttledShare >= t.throttledShare; | |
| const backlogged = queue.depth !== null && queue.depth > 0; | |
| const observedRate = queue.observedThroughputPerMin; | |
| const evidence = { | |
| backlogGrowing, | |
| throttledShare, | |
| envRunningShare, | |
| missing: null as WaitingRunDiagnosis["diagnosis"]["evidence"]["missing"], | |
| }; | |
| // Priority order copied from flow.ts: stall is a last-resort "it's on our side" cause, so a | |
| // known config bottleneck (queue throttling) must rule it out first. | |
| if ( | |
| hasConcurrencyEvidence && | |
| !queueThrottled && | |
| (envRunningShare as number) < t.stallRunningShare && | |
| backlogged && | |
| observedRate === 0 | |
| ) { | |
| return { cause: "stall", evidence }; | |
| } | |
| if (envPinned && backlogged) { | |
| return { cause: "env_limit_pinned", evidence }; | |
| } | |
| if (queueLimitPinned && backlogged) { | |
| return { cause: "queue_limit_pinned", evidence }; | |
| } | |
| if (queueThrottled && backlogged) { | |
| return { cause: "throttled", evidence }; | |
| } | |
| if (!backlogged || (observedRate !== null && observedRate > 0)) { | |
| return { cause: "draining_normally", evidence }; | |
| } | |
| // Backlogged with nothing moving, but no capacity evidence to say whether that's a limit or a | |
| // stall. flow.ts's lesson: don't name a concurrency cause without the evidence for it. | |
| return { cause: "unknown", evidence: { ...evidence, missing: "env_concurrency" } }; | |
| } | |
| function deriveCause( | |
| queue: WaitingRunDiagnosis["queue"], | |
| signals: WaitingRunQueueSignals | null | |
| ): { cause: WaitingRunCause; evidence: WaitingRunDiagnosis["diagnosis"]["evidence"] } { | |
| const t = HEALTH_THRESHOLDS.flowCause; | |
| if (!signals || queue.sampleBuckets === 0) { | |
| return { | |
| cause: "unknown", | |
| evidence: { | |
| backlogGrowing: false, | |
| throttledShare: queue.throttled.share, | |
| envRunningShare: null, | |
| missing: "queue_signals", | |
| }, | |
| }; | |
| } | |
| const backlogGrowing = isPendingIncreasing(signals.depthSeries); | |
| const throttledShare = queue.throttled.share; | |
| // Same guard as flow.ts `#1`: without a real limit AND a real running reading, a share is a | |
| // meaningless 0 that would falsely select `stall`. | |
| const hasConcurrencyEvidence = | |
| signals.envLimit !== null && signals.envLimit > 0 && signals.envRunning !== null; | |
| const envRunningShare = hasConcurrencyEvidence | |
| ? (signals.envRunning as number) / (signals.envLimit as number) | |
| : null; | |
| const envPinned = envRunningShare !== null && envRunningShare >= t.pinnedLevel; | |
| // A queue's own limit is visible through throttling: `throttled_count` counts exactly the | |
| // emissions where running >= limit while work was queued. Sustained (most of the window) | |
| // reads as pinned at the queue limit; intermittent reads as throttled. | |
| const queueLimitPinned = throttledShare >= t.pinnedShare; | |
| const queueThrottled = throttledShare >= t.throttledShare; | |
| const backlogged = queue.depth !== null && queue.depth > 0; | |
| const observedRate = queue.observedThroughputPerMin; | |
| const evidence = { | |
| backlogGrowing, | |
| throttledShare, | |
| envRunningShare, | |
| missing: null as WaitingRunDiagnosis["diagnosis"]["evidence"]["missing"], | |
| }; | |
| // Priority order copied from flow.ts: stall is a last-resort "it's on our side" cause, so a | |
| // known config bottleneck (queue throttling) must rule it out first. | |
| if ( | |
| hasConcurrencyEvidence && | |
| !queueThrottled && | |
| (envRunningShare as number) < t.stallRunningShare && | |
| backlogged && | |
| observedRate === 0 | |
| ) { | |
| return { cause: "stall", evidence }; | |
| } | |
| if (envPinned && backlogged) { | |
| return { cause: "env_limit_pinned", evidence }; | |
| } | |
| if (queueLimitPinned && backlogged) { | |
| return { cause: "queue_limit_pinned", evidence }; | |
| } | |
| if (queueThrottled && backlogged) { | |
| return { cause: "throttled", evidence }; | |
| } | |
| if (!backlogged || (observedRate !== null && observedRate > 0)) { | |
| return { cause: "draining_normally", evidence }; | |
| } | |
| // Backlogged with nothing moving, but no capacity evidence to say whether that's a limit or a | |
| // stall. flow.ts's lesson: don't name a concurrency cause without the evidence for it. | |
| return { | |
| cause: "unknown", | |
| evidence: { ...evidence, missing: hasConcurrencyEvidence ? null : "env_concurrency" }, | |
| }; | |
| } |
| // Default to the account email: the agent must not be able to point an alert at | ||
| // an address the user didn't give it. | ||
| let email = body.email; | ||
| if (!email) { | ||
| const user = await $replica.user.findFirst({ where: { id: userId }, select: { email: true } }); | ||
| if (!user) { | ||
| return json({ error: "User not found", code: "invalid_request" }, { status: 404 }); | ||
| } | ||
| email = user.email; | ||
| } | ||
|
|
||
| try { | ||
| const service = new CreateAlertChannelService(); | ||
| const channel = await service.call(environment.project.externalRef, userId, { | ||
| name: `Watch alerts for ${email}`, | ||
| alertTypes: [DASHBOARD_AGENT_WATCH_ALERT_TYPE], | ||
| environmentTypes: [environment.type], | ||
| // Stable per (email, project): asking twice re-enables the existing | ||
| // subscription instead of stacking duplicate channels. | ||
| deduplicationKey: `dashboard-agent-watch:${email}`, | ||
| channel: { type: "EMAIL", email }, | ||
| }); |
There was a problem hiding this comment.
🔒 Security & Privacy | 🟠 Major | 🏗️ Heavy lift
Any caller-supplied email is accepted, contradicting the stated intent.
The comment says the agent must not be able to point an alert at an address the user didn't give it, but body.email (Line 40) is only validated as a well-formed address — it isn't checked against the authenticated user's own email or org membership. A delegated agent token (or a prompt-injected agent) can therefore subscribe an arbitrary third-party address to this project's watch alerts, leaking watch details and creating a mail-sending vector. Also normalize the address before using it in deduplicationKey, otherwise User@x.com and user@x.com create two channels for the same mailbox.
🛡️ Proposed fix: restrict to the account email (or an org member's), and normalize
- let email = body.email;
- if (!email) {
- const user = await $replica.user.findFirst({ where: { id: userId }, select: { email: true } });
- if (!user) {
- return json({ error: "User not found", code: "invalid_request" }, { status: 404 });
- }
- email = user.email;
- }
+ const user = await $replica.user.findFirst({ where: { id: userId }, select: { email: true } });
+ if (!user) {
+ return json({ error: "User not found", code: "invalid_request" }, { status: 404 });
+ }
+ const accountEmail = user.email.trim().toLowerCase();
+ const requested = body.email?.trim().toLowerCase();
+ if (requested && requested !== accountEmail) {
+ return json(
+ { error: "Alerts can only be sent to your account email", code: "invalid_request" },
+ { status: 403 }
+ );
+ }
+ const email = accountEmail;📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| // Default to the account email: the agent must not be able to point an alert at | |
| // an address the user didn't give it. | |
| let email = body.email; | |
| if (!email) { | |
| const user = await $replica.user.findFirst({ where: { id: userId }, select: { email: true } }); | |
| if (!user) { | |
| return json({ error: "User not found", code: "invalid_request" }, { status: 404 }); | |
| } | |
| email = user.email; | |
| } | |
| try { | |
| const service = new CreateAlertChannelService(); | |
| const channel = await service.call(environment.project.externalRef, userId, { | |
| name: `Watch alerts for ${email}`, | |
| alertTypes: [DASHBOARD_AGENT_WATCH_ALERT_TYPE], | |
| environmentTypes: [environment.type], | |
| // Stable per (email, project): asking twice re-enables the existing | |
| // subscription instead of stacking duplicate channels. | |
| deduplicationKey: `dashboard-agent-watch:${email}`, | |
| channel: { type: "EMAIL", email }, | |
| }); | |
| // Default to the account email: the agent must not be able to point an alert at | |
| // an address the user didn't give it. | |
| const user = await $replica.user.findFirst({ where: { id: userId }, select: { email: true } }); | |
| if (!user) { | |
| return json({ error: "User not found", code: "invalid_request" }, { status: 404 }); | |
| } | |
| const accountEmail = user.email.trim().toLowerCase(); | |
| const requested = body.email?.trim().toLowerCase(); | |
| if (requested && requested !== accountEmail) { | |
| return json( | |
| { error: "Alerts can only be sent to your account email", code: "invalid_request" }, | |
| { status: 403 } | |
| ); | |
| } | |
| const email = accountEmail; | |
| try { | |
| const service = new CreateAlertChannelService(); | |
| const channel = await service.call(environment.project.externalRef, userId, { | |
| name: `Watch alerts for ${email}`, | |
| alertTypes: [DASHBOARD_AGENT_WATCH_ALERT_TYPE], | |
| environmentTypes: [environment.type], | |
| // Stable per (email, project): asking twice re-enables the existing | |
| // subscription instead of stacking duplicate channels. | |
| deduplicationKey: `dashboard-agent-watch:${email}`, | |
| channel: { type: "EMAIL", email }, | |
| }); |
| export async function authorizeWatchEnvironment(params: { | ||
| userId: string; | ||
| organizationId: string; | ||
| projectId: string; | ||
| environmentId: string; | ||
| }): Promise<WatchAuthorization> { | ||
| const environment = await $replica.runtimeEnvironment.findFirst({ | ||
| where: { | ||
| id: params.environmentId, | ||
| // The watch's snapshot has to still describe this environment — a mismatch | ||
| // means the row is being used to reach somewhere it was never created for. | ||
| projectId: params.projectId, | ||
| organizationId: params.organizationId, | ||
| archivedAt: null, | ||
| project: { deletedAt: null }, | ||
| organization: { deletedAt: null, members: { some: { userId: params.userId } } }, | ||
| OR: [ | ||
| { type: { in: ["PREVIEW", "STAGING", "PRODUCTION"] } }, | ||
| // Dev environments are per-member: only their owner may read them. | ||
| { type: "DEVELOPMENT", orgMember: { userId: params.userId } }, | ||
| ], | ||
| }, | ||
| include: authIncludeWithParent, | ||
| }); | ||
|
|
||
| if (!environment) return { ok: false, reason: "access_revoked" }; | ||
|
|
||
| const user = await $replica.user.findFirst({ | ||
| where: { id: params.userId }, | ||
| select: { admin: true }, | ||
| }); | ||
| if (!user) return { ok: false, reason: "access_revoked" }; | ||
|
|
||
| const allowed = await canAccessDashboardAgent({ | ||
| userId: params.userId, | ||
| isAdmin: user.admin, | ||
| // A background check is never an impersonated session. | ||
| isImpersonating: false, | ||
| organizationSlug: environment.organization.slug, | ||
| orgFeatureFlags: environment.organization.featureFlags as Record<string, unknown> | null, | ||
| }); | ||
| if (!allowed) return { ok: false, reason: "access_revoked" }; | ||
|
|
||
| return { ok: true, environment: toAuthenticated(environment) }; | ||
| } | ||
|
|
||
| /** | ||
| * The same authorization, addressed by environment id alone — for the creation | ||
| * path, where no watch row (and so no org/project snapshot to cross-check) exists | ||
| * yet. The id lookup is unscoped on purpose and proves nothing; every membership, | ||
| * dev-owner and feature-gate rule is applied by `authorizeWatchEnvironment` below | ||
| * it, so an id the user can't reach still resolves to `null`. | ||
| */ | ||
| export async function authorizeWatchEnvironmentById(params: { | ||
| userId: string; | ||
| environmentId: string; | ||
| }): Promise<AuthenticatedEnvironment | null> { | ||
| const environment = await $replica.runtimeEnvironment.findFirst({ | ||
| where: { id: params.environmentId }, | ||
| select: { organizationId: true, projectId: true }, | ||
| }); | ||
| if (!environment) return null; | ||
|
|
||
| const authorization = await authorizeWatchEnvironment({ | ||
| userId: params.userId, | ||
| organizationId: environment.organizationId, | ||
| projectId: environment.projectId, | ||
| environmentId: params.environmentId, | ||
| }); | ||
| return authorization.ok ? authorization.environment : null; | ||
| } |
There was a problem hiding this comment.
🔒 Security & Privacy | 🟠 Major | 🏗️ Heavy lift
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== locate file =="
fd -a 'dashboardAgentWatches\.server\.ts$' . || true
echo "== file outline =="
file="$(fd 'dashboardAgentWatches\.server\.ts$' . | head -n1 || true)"
if [ -n "${file:-}" ]; then
wc -l "$file"
ast-grep outline "$file" || true
echo "== relevant lines 1-180 =="
sed -n '1,180p' "$file" | nl -ba
fi
echo "== search authorization / replica usage in file =="
if [ -n "${file:-}" ]; then
rg -n '\$replica|authorizeWatchEnvironment|authorizeWatchEnvironmentById|runtimeEnvironment|canAccessDashboardAgent|findFirst|findUnique' "$file" || true
fi
echo "== db client definitions for replica/prisma =="
rg -n '\b\$replica\b|\bexport const prisma\b|\bexport const .*prisma\b|\bnew PrismaClient\b' . --glob '!node_modules' --glob '!dist' --glob '!build' | head -n 200Repository: triggerdotdev/trigger.dev
Length of output: 2044
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== repository root files =="
git ls-files apps/webapp/app/services/dashboardAgentWatches.server.ts || true
echo "== locate file =="
fd 'dashboardAgentWatches\.server\.ts$' . || true
echo "== file outline =="
file="$(fd 'dashboardAgentWatches\.server\.ts$' . | head -n1 || true)"
if [ -n "${file:-}" ]; then
wc -l "$file"
ast-grep outline "$file" || true
echo "== relevant lines 1-180 =="
sed -n '1,180p' "$file" | nl -ba
fi
echo "== search authorization / replica usage in file =="
if [ -n "${file:-}" ]; then
rg -n '\$replica|authorizeWatchEnvironment|authorizeWatchEnvironmentById|runtimeEnvironment|canAccessDashboardAgent|findFirst|findUnique' "$file" || true
fi
echo "== db client definitions for replica/prisma =="
rg -n '\b\$replica\b|\bexport const prisma\b|\bexport const .*prisma\b|\bnew PrismaClient\b' . --glob '!node_modules' --glob '!dist' --glob '!build' | head -n 200Repository: triggerdotdev/trigger.dev
Length of output: 2044
Run watch re-authorization against the primary Prisma client.
authorizeWatchEnvironment is the per-tick gate for runtimeEnvironment, org membership, dev-environment ownership, project deletion, and user/admin status. Reading these revocation-sensitive rows from $replica can allow a just-revoked user to pass while the replica is lagging, letting one more tick fire/deliver an alert on data they should no longer access. At minimum, use the primary client for the authorization-scoped runtimeEnvironment.findFirst and user.findFirst.
Source: Learnings
| await import("~/routes/api.v1.dashboard-agent.watches.$watchId.check"); | ||
| const { action: createAction } = await import("~/routes/api.v1.dashboard-agent.watches"); | ||
| const { signDashboardAgentWatchToken } = await import("~/services/dashboardAgentWatchToken.server"); | ||
| const { env } = await import("~/env.server"); |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win
Don't import env.server from a webapp test. env.SESSION_SECRET is only needed by tokenFor; pass the secret in as a parameter/constant instead so the test doesn't drag the env schema (and its required-var validation) into the suite.
As per coding guidelines: "Test files must not import app/env.server.ts; pass configuration as options instead."
Source: Coding guidelines
| const AGENT_MIGRATIONS = [ | ||
| "0000_magenta_lilandra", | ||
| "0001_slimy_living_tribunal", | ||
| "0002_luxuriant_king_cobra", | ||
| ]; | ||
|
|
||
| /** Apply the dashboard-agent schema by replaying its Drizzle migration SQL. */ | ||
| async function applyAgentSchema(prisma: PrismaClient) { | ||
| const folder = path.resolve(__dirname, "../../../internal-packages/dashboard-agent-db/drizzle"); | ||
| for (const name of AGENT_MIGRATIONS) { | ||
| const sql = readFileSync(path.join(folder, `${name}.sql`), "utf8"); | ||
| for (const statement of sql.split("--> statement-breakpoint")) { | ||
| const trimmed = statement.trim(); | ||
| if (trimmed.length > 0) await prisma.$executeRawUnsafe(trimmed); | ||
| } | ||
| } | ||
| } |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win
Hardcoded migration list will rot. This PR also adds internal-packages/dashboard-agent-db/drizzle/0003_famous_champions.sql, which this array omits — so the container schema silently lags the real one and any query touching the newer columns (e.g. chat read tracking) will fail or be untested. Read the migration set from drizzle/meta/_journal.json (or glob *.sql sorted) instead of listing names.
♻️ Derive the list from the journal
-const AGENT_MIGRATIONS = [
- "0000_magenta_lilandra",
- "0001_slimy_living_tribunal",
- "0002_luxuriant_king_cobra",
-];
-
/** Apply the dashboard-agent schema by replaying its Drizzle migration SQL. */
async function applyAgentSchema(prisma: PrismaClient) {
const folder = path.resolve(__dirname, "../../../internal-packages/dashboard-agent-db/drizzle");
- for (const name of AGENT_MIGRATIONS) {
+ const journal = JSON.parse(readFileSync(path.join(folder, "meta/_journal.json"), "utf8")) as {
+ entries: Array<{ tag: string }>;
+ };
+ for (const { tag: name } of journal.entries) {
const sql = readFileSync(path.join(folder, `${name}.sql`), "utf8");📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| const AGENT_MIGRATIONS = [ | |
| "0000_magenta_lilandra", | |
| "0001_slimy_living_tribunal", | |
| "0002_luxuriant_king_cobra", | |
| ]; | |
| /** Apply the dashboard-agent schema by replaying its Drizzle migration SQL. */ | |
| async function applyAgentSchema(prisma: PrismaClient) { | |
| const folder = path.resolve(__dirname, "../../../internal-packages/dashboard-agent-db/drizzle"); | |
| for (const name of AGENT_MIGRATIONS) { | |
| const sql = readFileSync(path.join(folder, `${name}.sql`), "utf8"); | |
| for (const statement of sql.split("--> statement-breakpoint")) { | |
| const trimmed = statement.trim(); | |
| if (trimmed.length > 0) await prisma.$executeRawUnsafe(trimmed); | |
| } | |
| } | |
| } | |
| /** Apply the dashboard-agent schema by replaying its Drizzle migration SQL. */ | |
| async function applyAgentSchema(prisma: PrismaClient) { | |
| const folder = path.resolve(__dirname, "../../../internal-packages/dashboard-agent-db/drizzle"); | |
| const journal = JSON.parse(readFileSync(path.join(folder, "meta/_journal.json"), "utf8")) as { | |
| entries: Array<{ tag: string }>; | |
| }; | |
| for (const { tag: name } of journal.entries) { | |
| const sql = readFileSync(path.join(folder, `${name}.sql`), "utf8"); | |
| for (const statement of sql.split("--> statement-breakpoint")) { | |
| const trimmed = statement.trim(); | |
| if (trimmed.length > 0) await prisma.$executeRawUnsafe(trimmed); | |
| } | |
| } | |
| } |
| /** | ||
| * The persisted spec adds a server-set `since` to the caller's spec. It's the | ||
| * watch's creation time (ISO), used by `error_recurrence` so a recurrence check | ||
| * can't match errors that predate the watch. Stored inside the JSONB rather than | ||
| * as a column because it's part of the check's input, not watch lifecycle state. | ||
| */ | ||
| export type PersistedWatchSpec = WatchSpec & { since?: string }; | ||
|
|
There was a problem hiding this comment.
🎯 Functional Correctness | 🔴 Critical | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
fd -t f 'schema.ts' internal-packages/dashboard-agent-db --exec rg -n 'PersistedWatchSpec' {}Repository: triggerdotdev/trigger.dev
Length of output: 2073
🏁 Script executed:
#!/bin/bash
set -u
echo "PWD: $(pwd)"
echo "Top-level git availability:"
git rev-parse --show-toplevel 2>/dev/null || echo "git unavailable/not repo"
echo
echo "Find schema.ts candidates:"
fd -t f 'schema\.ts$' . 2>/dev/null | sed -n '1,50p' | grep -E 'internal-packages/dashboard-agent-db/src/schema\.ts|schema\.ts$' || true
echo
echo "Search PersistedWatchSpec in available files:"
if [ -d internal-packages/dashboard-agent-db/src ]; then
rg -n 'PersistedWatchSpec' internal-packages/dashboard-agent-db/src 2>/dev/null || true
else
echo "internal-packages/dashboard-agent-db/src not present"
fi
echo
echo "Context around internal-packages/dashboard-agent-db/src/schema.ts if present:"
if [ -f internal-packages/dashboard-agent-db/src/schema.ts ]; then
sed -n '180,210p' internal-packages/dashboard-agent-db/src/schema.ts | cat -n
fiRepository: triggerdotdev/trigger.dev
Length of output: 2044
🏁 Script executed:
#!/bin/bash
set -u
if [ ! -f internal-packages/dashboard-agent-db/src/schema.ts ]; then
echo "target file missing from sandbox"
exit 0
fi
python3 - <<'PY'
from pathlib import Path
line = 199 # likely line number for duplicate duplicate based on 201-202 snippet duplicate
path = Path("internal-packages/dashboard-agent-db/src/schema.ts")
text = path.read_text()
needle = "export type PersistedWatchSpec = WatchSpec & { since?: string };"
parts = text.splitlines()
for n, s in enumerate(parts, 1):
if "PersistedWatchSpec" in s:
print(f"{n}: {s}")
print("\n occurrences:", len([s for s in parts if needle in s]))
print("around 190-205:")
for n, s in enumerate(parts[189:204], 190):
print(f"{n}: {s}")
PYRepository: triggerdotdev/trigger.dev
Length of output: 2044
Duplicate PersistedWatchSpec declaration.
internal-packages/dashboard-agent-db/src/schema.ts declares export type PersistedWatchSpec = WatchSpec & { since?: string }; twice in the same module, which causes a duplicate identifier compile error. Remove the duplicate declaration.
The M5 entry-point list promised it; only the error-group page had it.
… buttons A superlative question is answered in words with the top item's name and number; the chart illustrates. The chart block gains up to three actions (ask — the user's own follow-up, or navigate with a canonical trigger:// target), rendered as buttons under the chart and wired through the panel's existing intent handling. A navigate target is a plain string at the input boundary and a non-parsing one costs the button, never the tool call.
There was a problem hiding this comment.
Actionable comments posted: 8
Note
Due to the large number of review comments, Critical, Major severity comments were prioritized as inline comments.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
apps/webapp/app/presenters/v3/ApiAlertChannelPresenter.server.ts (1)
15-22: 🔒 Security & Privacy | 🟠 Major | ⚡ Quick winGate
dashboard_agent_watchfrom API alert-channel creation.
api.v1.projects.<projectRef>.alertChannelsparsesdashboard_agent_watchviaApiCreateAlertChannel, maps it toDASHBOARD_AGENT_WATCH, and persists it in the enabled alert channel. Add the samecanAccessDashboardAgentcheck used by the web app/agent alert path before saving that type, since PAT/API users can otherwise subscribe an enabled channel to watch alerts without dashboard-agent access.
🟡 Minor comments (14)
apps/webapp/app/services/uatRoutePreamble.server.ts-31-34 (1)
31-34: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winAccept case-insensitive Bearer schemes.
/^Bearer /rejects valid lowercasebearerauthorization schemes, causing UAT requests to fall through and be rejected. Match the scheme case-insensitively.Proposed fix
- ?.replace(/^Bearer /, "") + ?.replace(/^Bearer\s+/i, "")internal-packages/dashboard-agent-contracts/src/blocks.ts-470-525 (1)
470-525: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winTwo prose invariants aren't enforced alongside the two that are.
The
superRefineenforces "remediation ⇒ concluded" and "checkNext ⇒ inconclusive", but:
checkNextis guarded bylength > 0whileremediationis guarded only by!== undefined, socheckNext: []passes on aconcludedinvestigation whereasremediation: ""is rejected on an inconclusive one. The asymmetry lets a model send an emptycheckNexton any outcome.progress's description says "Only while in_progress" (Line 486) but nothing rejects it on a terminal outcome, so aconcludedcard can still carry a live-progress string that the renderer may show.Both are model-supplied fields, so the schema is the only gate.
🛠️ Proposed tightening
- if (investigation.remediation !== undefined && investigation.outcome !== "concluded") { + if (investigation.remediation?.trim() && investigation.outcome !== "concluded") { ctx.addIssue({ code: z.ZodIssueCode.custom, path: ["remediation"], message: "Only a concluded investigation can offer a fix.", }); } - if ( - investigation.checkNext !== undefined && - investigation.checkNext.length > 0 && - investigation.outcome !== "inconclusive" - ) { + if (investigation.checkNext?.length && investigation.outcome !== "inconclusive") { ctx.addIssue({ code: z.ZodIssueCode.custom, path: ["checkNext"], message: "`checkNext` belongs to an inconclusive investigation.", }); } + if (investigation.progress?.trim() && investigation.outcome !== "in_progress") { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + path: ["progress"], + message: "`progress` only belongs to an in_progress investigation.", + }); + }internal-packages/dashboard-agent-contracts/src/watch.ts-29-34 (1)
29-34: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
maxHoursaccepts fractional values below one cadence interval.
z.number().positive().max(24)admits e.g.0.01, which yields anexpiresAtearlier than the minimum 1-minute cadence — the first tick is then alreadyfinaland the watch immediately expires as "not met by expiry". Since this value comes from the model, an integer floor of 1 keeps the lifecycle sane.🛡️ Proposed fix
- maxHours: z.number().positive().max(WATCH_MAX_HOURS), + maxHours: z.number().int().min(1).max(WATCH_MAX_HOURS),apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.alerts.new/route.tsx-460-471 (1)
460-471: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winThe "Dashboard agent watches" checkbox isn't feature-gated. Every project sees this option, including orgs without dashboard-agent access, where the alert type can never fire. Consider gating it on the same access check the rest of the feature uses (surface a flag from the loader).
apps/webapp/app/v3/services/alerts/deliverDashboardAgentWatchAlert.server.ts-396-404 (1)
396-404: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick winScalar fact values are never length-capped.
The doc comment promises "a cap so a big bag can't blow up an email or a Slack block", but only object values are truncated —
String(value)for a long string passes through unbounded. An oversized fact produces an invalid Slack block, which#postSlackMessagemaps toinvalid_blocks→SkipRetryError, silently dropping the notification.🐛 Proposed fix
.map(([key, value]) => ({ label: humanizeFactKey(key), - value: typeof value === "object" ? JSON.stringify(value).slice(0, 200) : String(value), + value: (typeof value === "object" ? JSON.stringify(value) : String(value)).slice(0, 200), }));apps/webapp/app/components/dashboard-agent/demo/demo-chats.ts-527-573 (1)
527-573: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
watchCreatedAndWakemixes two unrelated watch scenarios.The title ("Tell me when the backlog drains"), the intent object (
demoIntents.watch, which wrapsdemoBacklogDrainWatch.spec— 5 min checks for up to 6h, queuedemo-backlog-drain), and theheaderWatches/{kind:"watches"}items (demoWatches.activeRow, which includesdemoBacklogDrainWatch) all describe the backlog-drain watch. But the actual user message ("Tell me when the retry finishes"), assistant confirmation ("I'll check every minute for up to 2 hours"), and wake narration are all aboutdemoRunFinishedWatch(the run-retry watch) instead. The cadence numbers in the intent'soutcometext (5 min/6h) directly contradict the assistant's own text (1 min/2h) a few lines later.This reads as if the chat was repurposed from a backlog-drain story to a run-retry story without updating the title/intent/watches references.
apps/webapp/app/components/dashboard-agent/demo/demo-chats.ts-726-762 (1)
726-762: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
docsAnswertitle doesn't match its content.Title is "How do I use batchTrigger?" but the user question, the
search_docstool call, and the entire answer are about retry/exponential-backoff behavior —batchTriggeris never mentioned.🐛 Suggested fix
- title: "How do I use batchTrigger?", + title: "How do retries actually work?",apps/webapp/app/components/dashboard-agent/demo/demo-chats.ts-478-500 (1)
478-500: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
navigateRejectedIntenttitle doesn't match its content.Title is "Take me to my deployments" (a navigation request), but the actual turn is "Just fix it for me" being rejected via
demoIntents.proposeFix— unrelated to deployments or navigation. This is thehistory-list title, so it will mislead anyone browsing the demo chat registry in Storybook.🐛 Suggested fix
- title: "Take me to my deployments", + title: "Just fix it for me",apps/webapp/app/components/dashboard-agent/demo/demo-chats.ts-180-230 (1)
180-230: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
investigateConcludednarration undercounts the hypotheses it actually tested.The summary ("four tested hypotheses," line 185), the reasoning part ("Four candidates... run all four," lines 197-199), and the closing text ("Two of the four hold up," line 224) all describe a 4-hypothesis investigation. But
demoInvestigationConcludedinfixtures/investigation.ts(lines 245-286) actually has 5 hypotheses — it also includeshyp-queue-burst(validated), so 3 of 5 hold up, not 2 of 4. The remediation text (line 244, "cap the queue's concurrency...") relies on that 5th hypothesis, so the data looks like the intended/complete version and the narration is stale.For contrast, the sibling
investigateInconclusivechat correctly matches its narration to its 3-hypothesis fixture, so this looks like an oversight specific to this chat rather than an intentional simplification.🐛 Suggested fix
- reasoningPart( - "Four candidates: the provider's rate limit, a bad payload, the retry schedule, and yesterday's deploy. Each one has a check that can rule it out, so run all four before writing a conclusion." - ), + reasoningPart( + "Five candidates: the provider's rate limit, a bad payload, the retry schedule, yesterday's deploy, and the queue bursting into the provider. Each one has a check that can rule it out, so run all five before writing a conclusion." + ),and update the closing text/summary counts ("three of the five hold up") to match.
apps/webapp/app/components/dashboard-agent/demo/demo-chats.ts-575-617 (1)
575-617: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
watchExpiryAndCancelnarration miscounts the watches shown.The opening narration says: "Four watches from this conversation... One is still live... the rest have finished." But
demoWatches.row(used for bothheaderWatchesand the{kind:"watches"}item) has 5 entries, and 2 of them (demoRunFinishedWatchanddemoBacklogDrainWatch) areactive, not 1. So the actual chip row a reviewer sees will show 5 chips with 2 active ones, contradicting the "four... one still live" framing.🐛 Suggested fix
Either narrate 5 watches with 2 still live, or scope the displayed row to the 4 the story actually describes (excluding `demoBacklogDrainWatch`, which belongs to a different scenario):-{ kind: "watches", watches: demoWatches.row }, +{ kind: "watches", watches: [demoRunFinishedWatch, demoErrorRecurrenceWatch, demoHealthRecoveryWatch, demoCancelledWatch] },internal-packages/dashboard-agent/src/tools.ts-429-448 (1)
429-448: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
await res.text()can throw past the{ error }contract.The
fetchis guarded, but body reading isn't. On an abort (the 30s timeout at Line 1177) or a mid-stream socket reset,res.text()rejects and the exception escapessearchTriggerDocs, sosearch_docsthrows instead of returning{ error }— the convention this file states explicitly elsewhere ("Tools return {error}, never throw").🛡️ Proposed fix
if (!res.ok) return { error: `The docs search failed (status ${res.status}).` }; - const body = await res.text(); + let body: string; + try { + body = await res.text(); + } catch (error) { + return { error: `Couldn't read the docs response: ${(error as Error).message}` }; + } let payload: any;apps/webapp/app/components/dashboard-agent/agent-badges.tsx-46-46 (1)
46-46: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winUse React’s component prop typing for the badge icon map.
@heroicons/reactexportsForwardRefExoticComponent, not a function returningJSX.Element, so the direct assignments at lines 99, 127, and 155 may failtypecheck. Type this asReact.ComponentType<{ className?: string }>instead.apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx-163-180 (1)
163-180: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick winRender citation same-origin paths in a client-only SSR-safe way.
sameOriginPath(...)cannot work during SSR becauselocationis browser-only, whilewindowis falsy in the server pass. For same-origin citations, wrap this inClientOnly/SSR-safe rendering so SSR passes the browser-readyButtonbranch and avoids a new-tabLinkButtonvs clientButtonmismatch.apps/webapp/app/components/dashboard-agent/suggested-prompts/promotedPrompt.server.ts-26-36 (1)
26-36: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick winIsolate the decorated flag read so the promoted chip can’t fail the environment layout.
makeFlag()readsprisma.featureFlag.findFirst()without catching Prisma failures, and this helper is awaited directly from the environment page loader. A flag-store hiccup on this optional, unsupported chip can turn the whole page into a 500, so catch and returnundefinedinstead.🛡️ Proposed fix
- const flag = makeFlag(); - const value = await flag({ - key: FEATURE_FLAG.promotedDashboardAgentPrompt, - overrides: options?.orgFeatureFlags ?? {}, - }); - - return parsePromotedPrompt(value); + try { + const flag = makeFlag(); + const value = await flag({ + key: FEATURE_FLAG.promotedDashboardAgentPrompt, + overrides: options?.orgFeatureFlags ?? {}, + }); + + return parsePromotedPrompt(value); + } catch { + // A missing promoted chip is a supported state; a flag-store hiccup must not + // fail the layout loader. + return undefined; + }
🧹 Nitpick comments (26)
apps/webapp/seed-agent-examples.mts (1)
2267-2296: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winWrap the tick in a try/catch so one transient failure doesn't end the heartbeat.
The loop awaits
heartbeatTickwith no error handling, andheartbeatTickitself has failure modes that are likely over a multi-hour run:prisma.taskRun.updateonexecutingRunId(Lines 2145-2150) throwsP2025once that row is gone (e.g. a re-seed or manual delete), and the ClickHouse insert helpers callprocess.exit(1). Net effect: the stand silently stops being refreshed and the report ages into "stale telemetry" — exactly what heartbeat mode exists to prevent.♻️ Suggested resilience for the tick loop
const counts: string[] = []; for (const env of envs) { - const result = await heartbeatTick(ch, env, started, rng, nonce, tick, mode); - counts.push( - `${env.environment.slug} +${result.runs} runs +${result.metricRows} metric rows` + - (result.pruned > 0 ? ` -${result.pruned} pruned` : "") - ); + try { + const result = await heartbeatTick(ch, env, started, rng, nonce, tick, mode); + counts.push( + `${env.environment.slug} +${result.runs} runs +${result.metricRows} metric rows` + + (result.pruned > 0 ? ` -${result.pruned} pruned` : "") + ); + } catch (error) { + counts.push( + `${env.environment.slug} tick failed: ${error instanceof Error ? error.message : error}` + ); + } }And make the executing-run touch tolerant of a missing row:
if (env.executingRunId) { - await prisma.taskRun.update({ - where: { id: env.executingRunId }, - data: { updatedAt: new Date(now) }, - }); + const { count } = await prisma.taskRun.updateMany({ + where: { id: env.executingRunId }, + data: { updatedAt: new Date(now) }, + }); + if (count === 0) env.executingRunId = null; }internal-packages/dashboard-agent/src/watch-tick.ts (1)
139-155: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick winValidate
body.resultagainstwatchCheckResultSchemainstead of casting.
body.resultis cast toWatchCheckResultwith no runtime check, and only three of the four values are matched explicitly inrunWatchTick. Any unexpected string falls into thependingbranch and the watch keeps ticking until expiry. The contracts package already exports the enum schema.♻️ Proposed change
-import type { WatchCheckResult } from "`@internal/dashboard-agent-contracts`"; +import { watchCheckResultSchema } from "`@internal/dashboard-agent-contracts`"; +import type { WatchCheckResult } from "`@internal/dashboard-agent-contracts`";- if (!body?.result) return { kind: "unavailable", detail: "the check returned no result" }; - if (body.result === "unavailable") return { kind: "unavailable", detail: body.error }; - return { kind: "result", result: body.result, facts: body.facts }; + const result = watchCheckResultSchema.safeParse(body?.result); + if (!result.success) { + return { kind: "unavailable", detail: "the check returned no usable result" }; + } + if (result.data === "unavailable") return { kind: "unavailable", detail: body?.error }; + return { kind: "result", result: result.data, facts: body?.facts };internal-packages/dashboard-agent-contracts/src/watch.ts (1)
38-61: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winUse
z.discriminatedUnion("kind", …)forwatchSpecSchema.Each variant already has a
kinddiscriminator, and this is the validated model input, so the targeted faster parsing and branch-specific validation error are worthwhile.♻️ Proposed change
-export const watchSpecSchema = z.union([ +export const watchSpecSchema = z.discriminatedUnion("kind", [internal-packages/dashboard-agent-db/src/queries.ts (1)
600-609: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueUse
typealiases for these data shapes.
ActiveWatchSummary,UnreadWatchWake, andChatWatchContextare plain data shapes, not behavioral contracts.As per coding guidelines: "Use types over interfaces for TypeScript".
♻️ Proposed change
-export interface ActiveWatchSummary { +export type ActiveWatchSummary = {(and likewise for
UnreadWatchWake/ChatWatchContext)Also applies to: 701-709, 790-794
Source: Coding guidelines
internal-packages/dashboard-agent/VERDICTS.md (1)
70-71: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valuePoint the
{env}citation attrigger-uri.ts.
trigger-uri.tsis where thetrigger://URI grammar is defined and documents{env}as the RuntimeEnvironment id;page-context.tsonly defines the page-context schema.internal-packages/dashboard-agent/src/dashboard-agent.test.ts (1)
414-433: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winFixed 30 ms sleep can flake on loaded CI.
onTurnCompleteenqueues asynchronously; a hard-coded delay is the only thing keeping these three assertions honest. Consider polling with a short deadline instead.♻️ Poll instead of sleeping
- await harness.sendMessage(userMessage("hi")); - // onTurnComplete enqueues after the turn-complete chunk; give it a tick. - await new Promise((r) => setTimeout(r, 30)); - return calls; + await harness.sendMessage(userMessage("hi")); + // onTurnComplete enqueues after the turn-complete chunk; wait for it (or + // settle) rather than betting on a fixed delay. + const deadline = Date.now() + 2000; + while (calls.length === 0 && Date.now() < deadline) { + await new Promise((r) => setTimeout(r, 10)); + } + return calls;Note the rate-0 case still needs a short settle window, so keep a small final tick for it.
apps/webapp/app/routes/api.v1.projects.$projectRef.$env.runs.$runId.commit.ts (1)
66-73: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick winSecond deployment lookup is redundant and replica-lag prone.
resolveRunCommitalready reads the deployment row withgitselected on the primary (apps/webapp/app/services/dashboardAgent.server.tsLines 224–229), then this route re-reads the same row from$replicakeyed by version. Besides the extra query, a freshly created deployment that resolved on the primary may not be visible on the replica yet, silently droppingshortCode/deployedAt/gitfrom the response. Consider havingresolveRunCommitreturn the git metadata (andshortCode/deployedAt) it already has.apps/webapp/test/dashboardAgentRoutes.test.ts (1)
26-29: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winThis
env.servermock is a no-op that still loads the real module.
importOriginal()evaluates~/env.server, so its env-var validation runs and the suite depends on the ambient environment — while the mock itself changes nothing. Either drop thevi.mockentirely or return explicit stub values for the keys the routes read.As per path instructions: "Do not import
env.server.tsdirectly or indirectly into test files; instead pass environment-dependent values through options/parameters to make code testable".Source: Path instructions
apps/webapp/test/dashboardAgentWatches.test.ts (2)
83-83: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winDon't import
env.serverin the test; pass the signing secret in.
envis only used at Line 676 to readSESSION_SECRETforsignDashboardAgentWatchToken. Use a literal test secret so the suite doesn't depend on the real env module loading and validating.As per coding guidelines: "Test files must not import
app/env.server.ts; pass configuration as options instead."♻️ Proposed change
-const { env } = await import("~/env.server"); +const TEST_SESSION_SECRET = "test-session-secret";function tokenFor(watchId: string, expiresAt: Date) { - return signDashboardAgentWatchToken(env.SESSION_SECRET, { watchId, expiresAt }); + return signDashboardAgentWatchToken(TEST_SESSION_SECRET, { watchId, expiresAt }); }Note: the route verifies with the real
env.SESSION_SECRET, so this only works if the route's secret is also injected or the test setsprocess.env.SESSION_SECRETbefore import — worth confirming which seam you prefer.Source: Coding guidelines
92-104: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueLexicographic migration ordering is fragile.
readdirSync().sort()matches the journal order only while every filename keeps a zero-padded numeric prefix.drizzle/meta/_journal.jsonis the authoritative order — readingidx/tagfrom it would make this replay correct by construction rather than by convention.apps/webapp/app/services/dashboardAgentWatchChecks.ts (1)
102-122: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winUse the shared
FINAL_RUN_STATUSESset for run terminality.
FINAL_STATUSESduplicatesapps/webapp/app/v3/taskStatus.FINAL_RUN_STATUSESand can silently drift if a terminal status changes. Since this file only imports isomorphic utilities forErrorIdand durations, avoid importing the mostly server-side~/v3/taskStatusmodule here; instead split the shared status constants/constants into an isomorphic helper and import it from this module.apps/webapp/app/routes/api.v1.queues.$queueParam.metrics.ts (1)
23-24: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winNarrow
UNIT_MSso period multiplications stay type-exact.
UNIT_MSis annotated asRecord<string, number>, and these app configs enablestrictmode but notnoUncheckedIndexedAccess, so the*inUNIT_MS[p.slice(-1)]andUNIT_MS.dis typed asnumberregardless of the actual key set. Use a keyedPeriodUnitvalue and narrow the index so the compiler rejects invalid suffixes before they can affect the refiner orperiodMs().Also applies to: 42-44
apps/webapp/app/routes/storybook.agent-ui/route.tsx (1)
437-459: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winOrphaned doc comment: the URI-resolver doc is attached to
investigationBlock.The block at Lines 437-441 documents
fixtureResolveUri, but that function is defined at Line 518; here it sits immediately above a second JSDoc forinvestigationBlock, leaving two stacked comments and the resolver undocumented at its definition.♻️ Move the resolver doc to its definition
-/** - * The gallery's stand-in for the panel's URI resolver. In the app the host - * resolves against the real environment (`resolveTriggerUri.server.ts`); here a - * fixture resolver proves the seam exists without a project route. - */ /** * The demo investigation fixtures, as the real `investigation` block: the demoAnd at Line 518:
+/** + * The gallery's stand-in for the panel's URI resolver. In the app the host + * resolves against the real environment (`resolveTriggerUri.server.ts`); here a + * fixture resolver proves the seam exists without a project route. + */ function fixtureResolveUri(uri: string): { label: string; url: string } | null {apps/webapp/scripts/agent-ui-screenshots.ts (1)
220-243: 🩺 Stability & Availability | 🔵 Trivial | 💤 Low valuePanel presence check may short-circuit when the panel is in the DOM but hidden.
openPanelreturns early oncount() > 0, so if the panel element persists while closed (e.g. mounted but translated/hidden), the launcher is never clicked and the subsequentcapture(panel)screenshots a collapsed element. Gating on visibility instead is more robust for the chat walk.🛠️ Gate on visibility
- const panel = page.locator(PANEL_SELECTOR); - if (!(await panel.count())) { + const panel = page.locator(PANEL_SELECTOR); + if (!(await panel.isVisible().catch(() => false))) {apps/webapp/app/components/dashboard-agent/demo/fixtures/intents.ts (1)
71-74: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAvoid duplicating the investigation id as a string literal.
investigationId: "demo:investigation-order-receipt"duplicates whatfixtures/investigation.tsalready computes asdemoId("investigation-order-receipt")fordemoInvestigationConcluded. Importing that value avoids silent drift if the investigation fixture's id is ever renamed.♻️ Suggested fix
-import { isExecutableIntent, type AgentIntent } from "`@internal/dashboard-agent-contracts`"; +import { isExecutableIntent, type AgentIntent } from "`@internal/dashboard-agent-contracts`"; +import { demoInvestigationConcluded } from "./investigation"; import { DEMO_WORLD, demoRunUri } from "../ids"; ... export const demoProposeFixIntent = demoIntent( - { kind: "propose_fix", investigationId: "demo:investigation-order-receipt" }, + { kind: "propose_fix", investigationId: demoInvestigationConcluded.investigationId }, "Rejected: proposing a fix isn't available yet" );apps/webapp/app/components/dashboard-agent/RunDiagnosisCard.tsx (1)
79-81: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winRaw indigo palette classes bypass the theme-remapping layer. Both new styles hardcode Tailwind palette classes, while
agent-badges.tsx(lines 30-31) andreport-sparkline.tsx(lines 39-40) added in this same PR explicitly state that palette classes are tuned for the dark theme only and that semantic tokens are what the theme layer remaps.
apps/webapp/app/components/dashboard-agent/RunDiagnosisCard.tsx#L79-L81: replaceLINK_STYLE'stext-indigo-500 hover:text-indigo-400with thetext-text-linktoken already used byInvestigationCard.tsx(line 89) andReportFooterLink.apps/webapp/app/components/primitives/Callout.tsx#L63-L70: give theagentvariant a semantic token (e.g. acallout-agenttoken alongside the existingcallout-docs/callout-pricingtokens) instead ofborder-indigo-500/20,bg-indigo-500/10andtext-indigo-500.apps/webapp/app/components/primitives/Callout.tsx (1)
63-70: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueRaw indigo palette classes won't be remapped by the theme layer.
Every other variant in this map uses semantic tokens (
callout-docs,success,warning,error); theagentframe and icon hardcodeindigo-500. See the consolidated note withRunDiagnosisCard.tsxfor the shared fix.apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx (1)
117-140: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winRaw
"output-error"string literal comparison.
p.state === "output-error"is compared as a raw literal here; the same literal is duplicated inreport-block-adapter.tsandAgentMessageView.tsx. See consolidated comment for a shared-constant suggestion.Source: Coding guidelines
apps/webapp/app/components/dashboard-agent/chat-layout.tsx (1)
236-284: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win
ChatToolRow/ChatStatusLinedon't self-apply the transcript inset when mounted loose.Per rule 2 in this file's own docstring, a micro-layout mounted outside a
ChatTurnmust apply the inset itself (ChatProgress,ChatPendingTool,ChatNoteall do this viauseInsetClass()).ChatToolRowandChatStatusLinedon't calluseInsetClass(), so if either is ever mounted loose (e.g. a tool row under a card), it will render without the horizontal inset, breaking alignment with the rest of the transcript. Neither is exercised in this diff yet, so confirm whether they're intentionally turn-only.apps/webapp/app/components/dashboard-agent/report-block-adapter.ts (1)
50-56: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winRaw
"output-available"string literal comparison.Same sentinel-value pattern as in
DashboardAgentMessages.tsxandAgentMessageView.tsx— see consolidated comment.Source: Coding guidelines
apps/webapp/app/components/runs/v3/agent/AgentMessageView.tsx (2)
164-188: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winRaw tool-part state string literals.
This function is the biggest concentration of raw AI-SDK tool-part state comparisons (
"output-error","input-streaming","input-available","approval-requested","approval-responded","output-denied") in the reviewed diff. See consolidated comment for a shared-constant suggestion.Source: Coding guidelines
1-1: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winExtract shared named constants for AI-SDK tool-part state strings.
AgentMessageView.tsx,DashboardAgentMessages.tsx, andreport-block-adapter.tseach independently comparep.stateagainst raw literals ("output-error","output-available","input-streaming","input-available","approval-requested","approval-responded","output-denied").progress-line.ts'sIN_FLIGHT_TOOL_STATESalready shows the right pattern for two of these; extending it (or a sibling constants module) to cover the rest would remove the duplication and the risk of a typo silently breaking one of these comparisons in a state machine that several files rely on independently.
apps/webapp/app/components/runs/v3/agent/AgentMessageView.tsx#L164-188: replace the raw"output-error","input-streaming","input-available","approval-requested","approval-responded","output-denied"literals with shared named constants.apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx#L117-140: replace the raw"output-error"literal inrenderDashboardPartwith the same shared constant.apps/webapp/app/components/dashboard-agent/report-block-adapter.ts#L50-56: replace the raw"output-available"literal with the same shared constant.Source: Coding guidelines
apps/webapp/app/presenters/v3/waitingRun/waitingRunDiagnosis.server.ts (1)
153-161: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low valueCarry-forward seed of
0can understate early buckets.Buckets before the first emission are filled with
0rather than left unknown, so a queue whose first metric row lands mid-window renders a fake "empty then spike" shape in the sparkline.sampleBucketsprotects the ETA, but the series itself is user-visible. Consider starting from the first observed bucket (e.g. skip leading positions untilbyIndexhas a value, or backfill with the first known depth).apps/webapp/app/components/dashboard-agent/suggested-prompts/registry.ts (1)
217-222: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win
SIGNAL_PRIORITYis not exhaustiveness-checked, unlikeSIGNAL_SLOT.Both
contextualPromptsandcontextualPromptsBySlotiterateSIGNAL_PRIORITY, so a signal kind added to the contract but omitted here produces no chip at all — silently, sinceAgentPageSignalKind[]accepts a partial list.SIGNAL_SLOT(aRecord) would fail to compile in the same situation; make the priority list fail the same way.♻️ Force a compile error on a missing kind
-export const SIGNAL_PRIORITY: AgentPageSignalKind[] = [ +export const SIGNAL_PRIORITY = [ "fresh_failure", "waiting_run", "slow_run", "concurrency_saturation", -]; +] as const satisfies readonly AgentPageSignalKind[] & + Record<0 | 1 | 2 | 3, AgentPageSignalKind>;Simpler alternative: derive it from the
SIGNAL_SLOTkeys and sort, or add a type-level assertion that the union ofSIGNAL_PRIORITY[number]equalsAgentPageSignalKind.apps/webapp/app/components/dashboard-agent/suggested-prompts/resolver.test.ts (1)
164-172: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winThis assertion becomes a tautology if the fixture's page kind changes.
toContain("")always passes, so the branch is silently self-disabling — exactly the case thethrow new Error("fixture changed")guards elsewhere in this file (lines 223, 228) exist to prevent. Narrow first instead.💚 Proposed fix
- const [failure] = resolveSuggestedPrompts(demoPageContexts.failedRun, { now: NOW }); - - expect(failure?.label).toBe("Why did this run fail?"); - expect(failure?.prompt).toContain( - demoPageContexts.failedRun.page.kind === "run" ? demoPageContexts.failedRun.page.runId : "" - ); - expect(failure?.prompt).toContain("12m ago"); + const page = demoPageContexts.failedRun.page; + if (page.kind !== "run") throw new Error("fixture changed"); + const [failure] = resolveSuggestedPrompts(demoPageContexts.failedRun, { now: NOW }); + + expect(failure?.label).toBe("Why did this run fail?"); + expect(failure?.prompt).toContain(page.runId); + expect(failure?.prompt).toContain("12m ago");apps/webapp/app/components/dashboard-agent/suggested-prompts/resolver.ts (1)
67-67: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueTruncation drops the docs chip, contradicting the "always last, always present" invariant.
slice(0, CAP)cuts from the tail, and docs is the last slot. Today the cap presumably equals the slot count, so nothing is dropped — but ifSUGGESTED_PROMPT_CAPis ever lowered, the documented guarantee (this file's header, andregistry.tsline 14) silently breaks in favour of a lower-priority chip. Reserving the docs slot before the cap, or assertingCAP >= PROMPT_SLOTS.length + 1at module load, keeps the invariant honest.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 1060fc18-ba04-495e-8289-4498890ecfe7
⛔ Files ignored due to path filters (1)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (209)
.server-changes/dashboard-agent-first-turn-error.md.server-changes/dashboard-agent-investigate.md.server-changes/dashboard-agent-watch-alerts.md.server-changes/dashboard-agent-watches.md.server-changes/queue-metrics-api.md.server-changes/remove-header-docs-buttons.mdapps/webapp/.gitignoreapps/webapp/app/components/dashboard-agent/AgentChart.tsxapps/webapp/app/components/dashboard-agent/DashboardAgent.tsxapps/webapp/app/components/dashboard-agent/DashboardAgentChat.tsxapps/webapp/app/components/dashboard-agent/DashboardAgentComposer.tsxapps/webapp/app/components/dashboard-agent/DashboardAgentContextBanner.tsxapps/webapp/app/components/dashboard-agent/DashboardAgentDraft.tsxapps/webapp/app/components/dashboard-agent/DashboardAgentHeader.tsxapps/webapp/app/components/dashboard-agent/DashboardAgentHistory.tsxapps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsxapps/webapp/app/components/dashboard-agent/DashboardAgentPanel.tsxapps/webapp/app/components/dashboard-agent/DashboardAgentSuggestedPrompts.tsxapps/webapp/app/components/dashboard-agent/InvestigateButton.tsxapps/webapp/app/components/dashboard-agent/InvestigationCard.test.tsapps/webapp/app/components/dashboard-agent/InvestigationCard.tsxapps/webapp/app/components/dashboard-agent/ReportView.test.tsapps/webapp/app/components/dashboard-agent/ReportView.tsxapps/webapp/app/components/dashboard-agent/RunDiagnosisCard.tsxapps/webapp/app/components/dashboard-agent/WakeBanner.tsxapps/webapp/app/components/dashboard-agent/WatchChips.tsxapps/webapp/app/components/dashboard-agent/WatchWakeToast.tsxapps/webapp/app/components/dashboard-agent/agent-badges.tsxapps/webapp/app/components/dashboard-agent/chat-layout.test.tsapps/webapp/app/components/dashboard-agent/chat-layout.tsxapps/webapp/app/components/dashboard-agent/dashboardAgentLauncher.tsxapps/webapp/app/components/dashboard-agent/demo/components/DemoChartCard.tsxapps/webapp/app/components/dashboard-agent/demo/components/DemoIntentBubble.tsxapps/webapp/app/components/dashboard-agent/demo/components/DemoInvestigationCard.tsxapps/webapp/app/components/dashboard-agent/demo/components/DemoReportCard.tsxapps/webapp/app/components/dashboard-agent/demo/components/DemoSuggestedPromptsRow.tsxapps/webapp/app/components/dashboard-agent/demo/components/DemoWatchChips.tsxapps/webapp/app/components/dashboard-agent/demo/demo-chats.tsapps/webapp/app/components/dashboard-agent/demo/demo.test.tsapps/webapp/app/components/dashboard-agent/demo/fixtures/blocks.tsapps/webapp/app/components/dashboard-agent/demo/fixtures/chart.tsapps/webapp/app/components/dashboard-agent/demo/fixtures/index.tsapps/webapp/app/components/dashboard-agent/demo/fixtures/intents.tsapps/webapp/app/components/dashboard-agent/demo/fixtures/investigation.tsapps/webapp/app/components/dashboard-agent/demo/fixtures/messages.tsapps/webapp/app/components/dashboard-agent/demo/fixtures/page-context.tsapps/webapp/app/components/dashboard-agent/demo/fixtures/reports.tsapps/webapp/app/components/dashboard-agent/demo/fixtures/watches.tsapps/webapp/app/components/dashboard-agent/demo/ids.tsapps/webapp/app/components/dashboard-agent/demo/index.tsapps/webapp/app/components/dashboard-agent/investigate-prompts.test.tsapps/webapp/app/components/dashboard-agent/investigate-prompts.tsapps/webapp/app/components/dashboard-agent/list-row.tsxapps/webapp/app/components/dashboard-agent/message-order.test.tsapps/webapp/app/components/dashboard-agent/message-order.tsapps/webapp/app/components/dashboard-agent/navigate-target.test.tsapps/webapp/app/components/dashboard-agent/navigate-target.tsapps/webapp/app/components/dashboard-agent/page-context-types.tsapps/webapp/app/components/dashboard-agent/page-label.test.tsapps/webapp/app/components/dashboard-agent/page-label.tsapps/webapp/app/components/dashboard-agent/progress-line.test.tsapps/webapp/app/components/dashboard-agent/progress-line.tsapps/webapp/app/components/dashboard-agent/report-block-adapter.test.tsapps/webapp/app/components/dashboard-agent/report-block-adapter.tsapps/webapp/app/components/dashboard-agent/report-sparkline.tsxapps/webapp/app/components/dashboard-agent/run-id.test.tsapps/webapp/app/components/dashboard-agent/run-id.tsapps/webapp/app/components/dashboard-agent/suggested-prompts/dismissal.tsapps/webapp/app/components/dashboard-agent/suggested-prompts/index.tsapps/webapp/app/components/dashboard-agent/suggested-prompts/page-mappers.test.tsapps/webapp/app/components/dashboard-agent/suggested-prompts/page-mappers.tsapps/webapp/app/components/dashboard-agent/suggested-prompts/promoted.test.tsapps/webapp/app/components/dashboard-agent/suggested-prompts/promoted.tsapps/webapp/app/components/dashboard-agent/suggested-prompts/promotedPrompt.server.tsapps/webapp/app/components/dashboard-agent/suggested-prompts/registry.tsapps/webapp/app/components/dashboard-agent/suggested-prompts/resolver.test.tsapps/webapp/app/components/dashboard-agent/suggested-prompts/resolver.tsapps/webapp/app/components/dashboard-agent/tool-labels.test.tsapps/webapp/app/components/dashboard-agent/tool-labels.tsapps/webapp/app/components/dashboard-agent/useTranscriptAutoScroll.tsapps/webapp/app/components/dashboard-agent/view-blocks.test.tsapps/webapp/app/components/dashboard-agent/view-blocks.tsapps/webapp/app/components/dashboard-agent/view-catalog.tsxapps/webapp/app/components/dashboard-agent/watch-chips.test.tsapps/webapp/app/components/dashboard-agent/watch-chips.tsapps/webapp/app/components/metrics/MiniLineChart.tsxapps/webapp/app/components/primitives/Callout.tsxapps/webapp/app/components/runs/v3/agent/AgentMessageView.tsxapps/webapp/app/hooks/useAgentPageContext.tsapps/webapp/app/presenters/v3/ApiAlertChannelPresenter.server.tsapps/webapp/app/presenters/v3/reports/health/health-messages.tsapps/webapp/app/presenters/v3/reports/health/health.tsapps/webapp/app/presenters/v3/waitingRun/waitingRunDiagnosis.server.tsapps/webapp/app/presenters/v3/waitingRun/waitingRunDiagnosis.tsapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam._index/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.agents.$agentParam/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.alerts.new/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.alerts/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.apikeys/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.batches/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.branches/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.bulk-actions/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.deployments/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.dev-branches/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.environment-variables/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.errors.$fingerprint/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.limits/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.prompts._index/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.runs.$runParam/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.runs._index/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.sessions.$sessionParam/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.sessions._index/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.test/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.waitpoints.tokens/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.settings.private-connections._index/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.settings.private-connections.new/route.tsxapps/webapp/app/routes/account.tokens/route.tsxapps/webapp/app/routes/api.v1.dashboard-agent.alerts.$channelId.tsapps/webapp/app/routes/api.v1.dashboard-agent.alerts.tsapps/webapp/app/routes/api.v1.dashboard-agent.watches.$watchId.check.tsapps/webapp/app/routes/api.v1.dashboard-agent.watches.$watchId.fired.tsapps/webapp/app/routes/api.v1.dashboard-agent.watches.tsapps/webapp/app/routes/api.v1.projects.$projectRef.$env.jwt.tsapps/webapp/app/routes/api.v1.projects.$projectRef.$env.repo.snapshot.tsapps/webapp/app/routes/api.v1.projects.$projectRef.$env.runs.$runId.commit.tsapps/webapp/app/routes/api.v1.projects.$projectRef.$env.runs.$runId.waiting.tsapps/webapp/app/routes/api.v1.projects.$projectRef.$env.workers.$tagName.tsapps/webapp/app/routes/api.v1.queues.$queueParam.metrics.tsapps/webapp/app/routes/resources.dashboard-agent.alerts.$channelId.unsubscribe.tsxapps/webapp/app/routes/resources.orgs.$organizationSlug.projects.$projectParam.env.$envParam.dashboard-agent.in.$.tsapps/webapp/app/routes/resources.orgs.$organizationSlug.projects.$projectParam.env.$envParam.dashboard-agent.tsapps/webapp/app/routes/storybook.agent-ui/manifest.tsapps/webapp/app/routes/storybook.agent-ui/route.tsxapps/webapp/app/routes/storybook.callout/route.tsxapps/webapp/app/services/dashboardAgentAlertContext.server.tsapps/webapp/app/services/dashboardAgentAlertUnsubscribeToken.server.tsapps/webapp/app/services/dashboardAgentHeadStart.server.tsapps/webapp/app/services/dashboardAgentWatchAlerts.server.tsapps/webapp/app/services/dashboardAgentWatchChecks.server.tsapps/webapp/app/services/dashboardAgentWatchChecks.tsapps/webapp/app/services/dashboardAgentWatchToken.server.tsapps/webapp/app/services/dashboardAgentWatches.server.tsapps/webapp/app/services/resolveTriggerUri.server.tsapps/webapp/app/services/uatRoutePreamble.server.tsapps/webapp/app/utils/handle.tsapps/webapp/app/v3/alertsWorker.server.tsapps/webapp/app/v3/featureFlags.tsapps/webapp/app/v3/services/alerts/deliverAlert.server.tsapps/webapp/app/v3/services/alerts/deliverDashboardAgentWatchAlert.server.tsapps/webapp/package.jsonapps/webapp/scripts/agent-ui-screenshots.tsapps/webapp/seed-agent-examples-chats.mtsapps/webapp/seed-agent-examples.mtsapps/webapp/seed-queue-metrics.mtsapps/webapp/test/dashboardAgentHeadStart.test.tsapps/webapp/test/dashboardAgentRoutes.test.tsapps/webapp/test/dashboardAgentWatchChecks.test.tsapps/webapp/test/dashboardAgentWatchToken.test.tsapps/webapp/test/dashboardAgentWatches.test.tsapps/webapp/test/reportHealth.test.tsapps/webapp/test/resolveTriggerUri.test.tsapps/webapp/test/seedAgentExamplesChats.test.tsapps/webapp/test/waitingRunDiagnosis.test.tsapps/webapp/vitest.config.tsinternal-packages/dashboard-agent-contracts/package.jsoninternal-packages/dashboard-agent-contracts/src/blocks.test.tsinternal-packages/dashboard-agent-contracts/src/blocks.tsinternal-packages/dashboard-agent-contracts/src/contracts.test.tsinternal-packages/dashboard-agent-contracts/src/evidence.tsinternal-packages/dashboard-agent-contracts/src/index.tsinternal-packages/dashboard-agent-contracts/src/intent.tsinternal-packages/dashboard-agent-contracts/src/page-context.tsinternal-packages/dashboard-agent-contracts/src/run-filters.tsinternal-packages/dashboard-agent-contracts/src/suggested-prompts.tsinternal-packages/dashboard-agent-contracts/src/trigger-uri.test.tsinternal-packages/dashboard-agent-contracts/src/trigger-uri.tsinternal-packages/dashboard-agent-contracts/src/watch.test.tsinternal-packages/dashboard-agent-contracts/src/watch.tsinternal-packages/dashboard-agent-contracts/tsconfig.jsoninternal-packages/dashboard-agent-contracts/vitest.config.tsinternal-packages/dashboard-agent-db/README.mdinternal-packages/dashboard-agent-db/drizzle/0002_luxuriant_king_cobra.sqlinternal-packages/dashboard-agent-db/drizzle/0003_famous_champions.sqlinternal-packages/dashboard-agent-db/drizzle/meta/0002_snapshot.jsoninternal-packages/dashboard-agent-db/drizzle/meta/0003_snapshot.jsoninternal-packages/dashboard-agent-db/drizzle/meta/_journal.jsoninternal-packages/dashboard-agent-db/package.jsoninternal-packages/dashboard-agent-db/src/ids.tsinternal-packages/dashboard-agent-db/src/index.tsinternal-packages/dashboard-agent-db/src/queries.tsinternal-packages/dashboard-agent-db/src/schema.tsinternal-packages/dashboard-agent/GUIDEBOOK.mdinternal-packages/dashboard-agent/PLAYBOOK.mdinternal-packages/dashboard-agent/VERDICTS.mdinternal-packages/dashboard-agent/package.jsoninternal-packages/dashboard-agent/src/dashboard-agent.eval.tsinternal-packages/dashboard-agent/src/dashboard-agent.test.tsinternal-packages/dashboard-agent/src/dashboard-agent.tsinternal-packages/dashboard-agent/src/index.tsinternal-packages/dashboard-agent/src/tool-schemas.tsinternal-packages/dashboard-agent/src/tools.tsinternal-packages/dashboard-agent/src/watch-tick.test.tsinternal-packages/dashboard-agent/src/watch-tick.tsinternal-packages/dashboard-agent/vitest.eval.config.tsinternal-packages/database/prisma/migrations/20260729120000_add_dashboard_agent_watch_alert_type/migration.sqlinternal-packages/database/prisma/schema.prismainternal-packages/emails/emails/alert-dashboard-agent-watch.tsxinternal-packages/emails/src/index.tsx
💤 Files with no reviewable changes (1)
- apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.branches/route.tsx
| const gate = await canUseDashboardAgentEmailAlerts({ | ||
| userId, | ||
| organizationId: environment.organizationId, | ||
| organizationSlug: environment.organization.slug, | ||
| projectId: environment.project.id, | ||
| }); | ||
| if (!gate.allowed) { | ||
| return json({ error: "Alerts are not available here", code: gate.reason }, { status: 403 }); | ||
| } |
There was a problem hiding this comment.
🔒 Security & Privacy | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
fd 'dashboardAgentWatchAlerts.server.ts' --exec cat -n {}
rg -nP --type=ts -C3 'canUseDashboardAgent(Email)?Alerts\s*\(' appsRepository: triggerdotdev/trigger.dev
Length of output: 13203
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '--- locate canAccessDashboardAgent ---\n'
fd 'canAccessDashboardAgent.server.ts' --exec sh -c 'echo "### $1"; sed -n "1,220p" "$1" | cat -n' sh {}
printf '\n--- route slices ---\n'
for f in \
apps/webapp/app/routes/api.v1.dashboard-agent.alerts.ts \
apps/webapp/app/routes/api.v1.dashboard-agent.watches.ts \
apps/webapp/app/v3/services/alerts/deliverDashboardAgentWatchAlert.server.ts
do
echo "### $f"
lines="$(wc -l < "$f")"
case "$f" in
apps/webapp/app/routes/api.v1.dashboard-agent.alerts.ts) sed -n '80,140p' "$f" | cat -n ;;
apps/webapp/app/routes/api.v1.dashboard-agent.watches.ts) sed -n '145,205p' "$f" | cat -n ;;
apps/webapp/app/v3/services/alerts/deliverDashboardAgentWatchAlert.server.ts) sed -n '60,120p' "$f" | cat -n ;;
esac
doneRepository: triggerdotdev/trigger.dev
Length of output: 254
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '%s\n' '--- locate canAccessDashboardAgent ---'
fd 'canAccessDashboardAgent.server.ts' --exec sh -c 'echo "### $1"; sed -n "1,220p" "$1" | cat -n' sh {}
printf '%s\n' ''
printf '%s\n' '--- route slices ---'
for f in \
apps/webapp/app/routes/api.v1.dashboard-agent alerts.ts \
apps/webapp/app/routes/api.v1.dashboard-agent.watches.ts \
apps/webapp/app/v3/services/alerts/deliverDashboardAgentWatchAlert.server.ts
do
echo "### $f"
case "$f" in
'apps/webapp/app/routes/api.v1.dashboard-agent.alerts.ts') sed -n '80,140p' "$f" | cat -n ;;
'apps/webapp/app/routes/api.v1.dashboard-agent.watches.ts') sed -n '145,205p' "$f" | cat -n ;;
'apps/webapp/app/v3/services/alerts/deliverDashboardAgentWatchAlert.server.ts') sed -n '60,120p' "$f" | cat -n ;;
esac
doneRepository: triggerdotdev/trigger.dev
Length of output: 7125
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '%s\n' '--- all gate call sites with context ---'
rg -n -C 4 'canUseDashboardAgent(Email)?Alerts\s*\(' apps/webapp/app
printf '%s\n' ''
printf '%s\n' '--- imports and route context for alerts route ---'
f='apps/webapp/app/routes/api.v1.dashboard-agent.alerts.ts'
echo "### $f"
sed -n '1,150p' "$f" | cat -n
printf '%s\n' ''
echo "### apps/webapp/app/v3/services/alerts/deliverDashboardAgentWatchAlert.server.ts"
sed -n '1,130p' apps/webapp/app/v3/services/alerts/deliverDashboardAgentWatchAlert.server.ts | cat -n
printf '%s\n' ''
echo "### apps/webapp/app/routes/api.v1.dashboard-agent.watches.ts"
sed -n '1,220p' apps/webapp/app/routes/api.v1.dashboard-agent.watches.ts | cat -nRepository: triggerdotdev/trigger.dev
Length of output: 26440
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '%s\n' '--- imports in alerts route'
sed -n '1,30p' apps/webapp/app/routes/api.v1.dashboard-agent.alerts.ts | cat -n
printf '%s\n' ''
printf '%s\n' '--- import path for authenticateAgentUatOrApiRequest if present'
rg -n 'authenticateAgentUatOrApiRequest|resolveAgentAlertContext|organization.*featureFlags|featureFlags.*organization|Authenticated' apps/webapp/app/services -g '*.server.ts' -g '*.ts' | head -n 200Repository: triggerdotdev/trigger.dev
Length of output: 8407
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '%s\n' '--- dashboardAgentAlertContext.server.ts ---'
sed -n '1,220p' apps/webapp/app/services/dashboardAgentAlertContext.server.ts | cat -n
printf '%s\n' ''
printf '%s\n' '--- runtime environment auth slices mentioning organization select---'
rg -n -C 3 'authIncludeWithParent|toAuthenticated|organization.*featureFlags|featureFlags.*organization|authorizeWatchEnvironmentById|resolveAgentAlertContext' apps/webapp/app/services apps/webapp/app/models --glob '*.server.ts' --glob '*.ts' | head -n 300Repository: triggerdotdev/trigger.dev
Length of output: 21181
Align dashboard-agent alert gating across subscribe and delivery. The email subscribe route resolves its context via authorizeWatchEnvironmentById, which surfaces the org featureFlags and would allow using that in the 403 gate; resolveEmailAlertsState already passes it, but the delivery job selects only organization: { slug, title } and calls the gate without orgFeatureFlags. Select loaded by-reference org flags at delivery and thread them to canUseDashboardAgentAlerts so an org feature-override can’t allow subscribing while denying delivery, or vice versa.
📍 Affects 3 files
apps/webapp/app/routes/api.v1.dashboard-agent.alerts.ts#L122-L130(this comment)apps/webapp/app/v3/services/alerts/deliverDashboardAgentWatchAlert.server.ts#L104-L108apps/webapp/app/routes/api.v1.dashboard-agent.watches.ts#L180-L185
Source: Learnings
| params: z.object({ | ||
| queueParam: z.string().transform((val) => val.replace(/%2F/g, "/")), | ||
| }), | ||
| searchParams: SearchParamsSchema, | ||
| allowJWT: true, | ||
| corsStrategy: "none", | ||
| findResource: async () => 1, // dummy — the queue name isn't resolved against Postgres | ||
| authorization: { | ||
| action: "read", | ||
| resource: () => ({ type: "query", id: "queue_metrics" }), | ||
| }, | ||
| }, | ||
| async ({ params, searchParams, authentication }) => { | ||
| const name = decodeURIComponent(params.queueParam).replace(/%2F/g, "/"); | ||
| const queue = searchParams.type === "task" && !name.startsWith("task/") ? `task/${name}` : name; |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Queue name is decoded twice, and the second decode can throw a 500.
The params schema (Line 57) already unescapes %2F, and Remix has already URL-decoded the route param. Line 69 then runs decodeURIComponent on that value again plus a repeat %2F replace. Two consequences:
- A queue name containing a literal
%that isn't a valid escape (e.g.discount-100%) makesdecodeURIComponentthrowURIError. Line 69 sits outside thetrythat starts at Line 80, so it escapes the handler as an unhandled 500 rather than a 4xx. - Names with legitimately encoded characters get mangled by the extra decode pass.
Pick one place to normalize — the schema transform — and drop the second decode.
🐛 Proposed fix
params: z.object({
- queueParam: z.string().transform((val) => val.replace(/%2F/g, "/")),
+ // Remix has already URL-decoded the segment; only the `%2F` escape for the
+ // `task/` prefix survives and needs unescaping.
+ queueParam: z.string().transform((val) => val.replace(/%2F/gi, "/")),
}),- const name = decodeURIComponent(params.queueParam).replace(/%2F/g, "/");
+ const name = params.queueParam;
const queue = searchParams.type === "task" && !name.startsWith("task/") ? `task/${name}` : name;📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| params: z.object({ | |
| queueParam: z.string().transform((val) => val.replace(/%2F/g, "/")), | |
| }), | |
| searchParams: SearchParamsSchema, | |
| allowJWT: true, | |
| corsStrategy: "none", | |
| findResource: async () => 1, // dummy — the queue name isn't resolved against Postgres | |
| authorization: { | |
| action: "read", | |
| resource: () => ({ type: "query", id: "queue_metrics" }), | |
| }, | |
| }, | |
| async ({ params, searchParams, authentication }) => { | |
| const name = decodeURIComponent(params.queueParam).replace(/%2F/g, "/"); | |
| const queue = searchParams.type === "task" && !name.startsWith("task/") ? `task/${name}` : name; | |
| params: z.object({ | |
| // Remix has already URL-decoded the segment; only the `%2F` escape for the | |
| // `task/` prefix survives and needs unescaping. | |
| queueParam: z.string().transform((val) => val.replace(/%2F/gi, "/")), | |
| }), | |
| searchParams: SearchParamsSchema, | |
| allowJWT: true, | |
| corsStrategy: "none", | |
| findResource: async () => 1, // dummy — the queue name isn't resolved against Postgres | |
| authorization: { | |
| action: "read", | |
| resource: () => ({ type: "query", id: "queue_metrics" }), | |
| }, | |
| }, | |
| async ({ params, searchParams, authentication }) => { | |
| const name = params.queueParam; | |
| const queue = searchParams.type === "task" && !name.startsWith("task/") ? `task/${name}` : name; |
| const channel = await db.projectAlertChannel.findFirst({ | ||
| where: { id: channelId, ...(options.projectId ? { projectId: options.projectId } : {}) }, | ||
| select: { id: true, name: true, alertTypes: true }, | ||
| }); | ||
| if (!channel) return { ok: false, reason: "not_found" }; | ||
|
|
||
| const remaining = channel.alertTypes.filter((type) => type !== DASHBOARD_AGENT_WATCH_ALERT_TYPE); | ||
|
|
||
| await db.projectAlertChannel.update({ | ||
| where: { id: channel.id }, | ||
| data: { | ||
| alertTypes: remaining, | ||
| ...(remaining.length === 0 ? { enabled: false } : {}), | ||
| }, | ||
| }); |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
Make the unsubscribe update atomic.
The read at Line 179 and overwrite at Lines 187-193 can race with alert-channel edits, dropping newly added alert types or disabling a channel that was concurrently updated. Use a conditional-update/retry strategy or a database-side atomic array removal; compute enabled in that same atomic operation. As per coding guidelines, use the $transaction helper from ~/db.server with Serializable for correctness-critical read-then-write invariants.
Source: Coding guidelines
| const environment = await $replica.runtimeEnvironment.findFirst({ | ||
| where: { | ||
| id: params.environmentId, | ||
| // The watch's snapshot has to still describe this environment — a mismatch | ||
| // means the row is being used to reach somewhere it was never created for. | ||
| projectId: params.projectId, | ||
| organizationId: params.organizationId, | ||
| archivedAt: null, | ||
| project: { deletedAt: null }, | ||
| organization: { deletedAt: null, members: { some: { userId: params.userId } } }, | ||
| OR: [ | ||
| { type: { in: ["PREVIEW", "STAGING", "PRODUCTION"] } }, | ||
| // Dev environments are per-member: only their owner may read them. | ||
| { type: "DEVELOPMENT", orgMember: { userId: params.userId } }, | ||
| ], | ||
| }, | ||
| include: authIncludeWithParent, | ||
| }); | ||
|
|
||
| if (!environment) return { ok: false, reason: "access_revoked" }; | ||
|
|
||
| const user = await $replica.user.findFirst({ | ||
| where: { id: params.userId }, | ||
| select: { admin: true }, | ||
| }); |
There was a problem hiding this comment.
🔒 Security & Privacy | 🟠 Major | ⚡ Quick win
Re-authorization reads from $replica; use the primary client for the membership/tenant floor.
This query is the authorization boundary for every background tick (membership, live project, non-archived env, dev-owner), and replica lag makes it fail open: a membership that was just revoked, or an environment/project just archived/deleted, can still be visible on the replica, so the watch keeps firing with access the user no longer has. Same for the user.admin read feeding canAccessDashboardAgent. Read both from prisma and note why in a comment.
Based on learnings: whenever you resolve org/membership scope for RBAC/authorization, always read from the primary Prisma client (prisma), not $replica, because replica lag can cause the authorization check to run without the correct org scope.
🔒️ Proposed fix
- const environment = await $replica.runtimeEnvironment.findFirst({
+ // Primary client on purpose: replica lag on a revoked membership or a freshly
+ // archived environment would let this re-authorization pass open.
+ const environment = await prisma.runtimeEnvironment.findFirst({- const user = await $replica.user.findFirst({
+ const user = await prisma.user.findFirst({Update the import accordingly:
-import { $replica } from "~/db.server";
+import { $replica, prisma } from "~/db.server";📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| const environment = await $replica.runtimeEnvironment.findFirst({ | |
| where: { | |
| id: params.environmentId, | |
| // The watch's snapshot has to still describe this environment — a mismatch | |
| // means the row is being used to reach somewhere it was never created for. | |
| projectId: params.projectId, | |
| organizationId: params.organizationId, | |
| archivedAt: null, | |
| project: { deletedAt: null }, | |
| organization: { deletedAt: null, members: { some: { userId: params.userId } } }, | |
| OR: [ | |
| { type: { in: ["PREVIEW", "STAGING", "PRODUCTION"] } }, | |
| // Dev environments are per-member: only their owner may read them. | |
| { type: "DEVELOPMENT", orgMember: { userId: params.userId } }, | |
| ], | |
| }, | |
| include: authIncludeWithParent, | |
| }); | |
| if (!environment) return { ok: false, reason: "access_revoked" }; | |
| const user = await $replica.user.findFirst({ | |
| where: { id: params.userId }, | |
| select: { admin: true }, | |
| }); | |
| // Primary client on purpose: replica lag on a revoked membership or a freshly | |
| // archived environment would let this re-authorization pass open. | |
| const environment = await prisma.runtimeEnvironment.findFirst({ | |
| where: { | |
| id: params.environmentId, | |
| // The watch's snapshot has to still describe this environment — a mismatch | |
| // means the row is being used to reach somewhere it was never created for. | |
| projectId: params.projectId, | |
| organizationId: params.organizationId, | |
| archivedAt: null, | |
| project: { deletedAt: null }, | |
| organization: { deletedAt: null, members: { some: { userId: params.userId } } }, | |
| OR: [ | |
| { type: { in: ["PREVIEW", "STAGING", "PRODUCTION"] } }, | |
| // Dev environments are per-member: only their owner may read them. | |
| { type: "DEVELOPMENT", orgMember: { userId: params.userId } }, | |
| ], | |
| }, | |
| include: authIncludeWithParent, | |
| }); | |
| if (!environment) return { ok: false, reason: "access_revoked" }; | |
| const user = await prisma.user.findFirst({ | |
| where: { id: params.userId }, | |
| select: { admin: true }, | |
| }); |
Source: Learnings
| import { prisma } from "./app/db.server"; | ||
| import { createOrganization } from "./app/models/organization.server"; | ||
| import { createProject } from "./app/models/project.server"; | ||
| import { ClickHouse } from "@internal/clickhouse"; | ||
| import type { QueueMetricsRawV1Input } from "@internal/clickhouse"; | ||
| import { generateFriendlyId } from "./app/v3/friendlyIdentifiers"; |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Are these seeders declared as ESM entries, and how do the older ones import app modules?
fd -e mts . apps/webapp --max-depth 1
rg -n '"type"|db:seed' apps/webapp/package.json
rg -n '^import .* from "\./app/' apps/webapp/*.mtsRepository: triggerdotdev/trigger.dev
Length of output: 2326
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== apps/webapp/package.json scripts/types =="
python3 - <<'PY'
import json
from pathlib import Path
p=Path('apps/webapp/package.json')
data=json.loads(p.read_text())
for key in ['type','scripts']:
print(f'{key}: {data.get(key)!r}')
PY
echo "== relevant seeder comments and import usage =="
for f in apps/webapp/seed-agent-examples.mts apps/webapp/seed-ai-spans.mts apps/webapp/seed-agent-examples-chats.mts apps/webapp/seed-queue-metrics.mts; do
echo "--- $f (first 120 lines) ---"
sed -n '1,120p' "$f" | cat -n
done
echo "== tsconfig/module hints for webapp if present =="
fd -e 'tsconfig.*' -e 'package.json' apps/webapp . | sed -n '1,80p'
rg -n '"esModuleInterop"|"allowSyntheticDefaultImports"|"module"|"moduleResolution"|tsx"|"database"' apps/webapp -g '!node_modules' -g '!dist' -g '!build' | sed -n '1,200p'Repository: triggerdotdev/trigger.dev
Length of output: 25488
Use the default-binding import pattern for this .mts seeder.
apps/webapp has no "type": "module" and the seeder scripts compile app modules to CommonJS via tsx, so named imports from ./app/* can fail at startup. Align seed-queue-metrics.mts with seed-agent-examples.mts: import the compiled app modules as default bindings, then destructure the needed exports locally.
| import { | ||
| WATCH_TOKEN_GRACE_MS, | ||
| WATCH_TOKEN_PREFIX, | ||
| isDashboardAgentWatchToken, | ||
| signDashboardAgentWatchToken, | ||
| verifyDashboardAgentWatchToken, | ||
| } from "~/services/dashboardAgentWatchToken.server"; |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win
This test pulls in env.server transitively.
~/services/dashboardAgentWatchToken.server.ts imports env from ~/env.server at module scope, so importing it here loads the env schema/validation even though every assertion passes an explicit SECRET. Split the pure crypto (WATCH_TOKEN_PREFIX, WATCH_TOKEN_GRACE_MS, signDashboardAgentWatchToken, verifyDashboardAgentWatchToken, isDashboardAgentWatchToken) into a non-.server module and keep only the env-bound mint…/verify…FromRequest wrappers in .server.ts — the same seam split this PR already uses for dashboardAgentWatchChecks.ts vs dashboardAgentWatchChecks.server.ts. The test then imports the pure module.
As per path instructions: test files under apps/webapp must not import app/env.server.ts directly or indirectly; pass environment-dependent values through options/parameters instead.
Source: Path instructions
| export const evidenceSchema = z.object({ | ||
| /** What kind of resource this cites. Mirrors the URI's resource kinds. */ | ||
| kind: triggerUriKindSchema, | ||
| /** The resource itself. */ | ||
| uri: triggerUriSchema, | ||
| /** Short human label, e.g. "run_abc123 failed span" or "processOrder.ts:42". */ | ||
| label: z.string(), | ||
| /** Optional verbatim snippet (error message, log line, source lines). */ | ||
| excerpt: z.string().optional(), | ||
| }); |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
kind isn't cross-checked against the URI's own kind.
{ kind: "queue", uri: "trigger://proj_a/env_a/run/run_1" } validates, so a citation can claim one resource type and point at another — the renderer picks its icon/label from kind but resolves the link from uri. The demo suite already asserts this invariant on fixtures (apps/webapp/app/components/dashboard-agent/demo/demo.test.ts Lines 141-148 compare safeParseTriggerUri(evidence.uri).data.kind to evidence.kind), but nothing enforces it at the parse boundary where model-derived evidence actually arrives.
🛡️ Proposed fix
import { z } from "zod";
-import { triggerUriKindSchema, triggerUriSchema } from "./trigger-uri.js";
+import { safeParseTriggerUri, triggerUriKindSchema, triggerUriSchema } from "./trigger-uri.js";
-export const evidenceSchema = z.object({
+export const evidenceSchema = z
+ .object({
/** What kind of resource this cites. Mirrors the URI's resource kinds. */
kind: triggerUriKindSchema,
/** The resource itself. */
uri: triggerUriSchema,
/** Short human label, e.g. "run_abc123 failed span" or "processOrder.ts:42". */
label: z.string(),
/** Optional verbatim snippet (error message, log line, source lines). */
excerpt: z.string().optional(),
-});
+ })
+ .superRefine((evidence, ctx) => {
+ // A citation that claims one kind and points at another links the user
+ // somewhere other than what the card says it cites.
+ const parsed = safeParseTriggerUri(evidence.uri);
+ if (parsed.success && parsed.data.kind !== evidence.kind) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ["kind"],
+ message: `kind "${evidence.kind}" does not match the uri's kind "${parsed.data.kind}".`,
+ });
+ }
+ });Note this makes evidenceSchema a ZodEffects, so any consumer relying on .extend()/.merge()/.shape on it would need adjusting — in the current code it's only used as an array element in blocks.ts, which is fine.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| export const evidenceSchema = z.object({ | |
| /** What kind of resource this cites. Mirrors the URI's resource kinds. */ | |
| kind: triggerUriKindSchema, | |
| /** The resource itself. */ | |
| uri: triggerUriSchema, | |
| /** Short human label, e.g. "run_abc123 failed span" or "processOrder.ts:42". */ | |
| label: z.string(), | |
| /** Optional verbatim snippet (error message, log line, source lines). */ | |
| excerpt: z.string().optional(), | |
| }); | |
| import { z } from "zod"; | |
| import { safeParseTriggerUri, triggerUriKindSchema, triggerUriSchema } from "./trigger-uri.js"; | |
| export const evidenceSchema = z | |
| .object({ | |
| /** What kind of resource this cites. Mirrors the URI's resource kinds. */ | |
| kind: triggerUriKindSchema, | |
| /** The resource itself. */ | |
| uri: triggerUriSchema, | |
| /** Short human label, e.g. "run_abc123 failed span" or "processOrder.ts:42". */ | |
| label: z.string(), | |
| /** Optional verbatim snippet (error message, log line, source lines). */ | |
| excerpt: z.string().optional(), | |
| }) | |
| .superRefine((evidence, ctx) => { | |
| // A citation that claims one kind and points at another links the user | |
| // somewhere other than what the card says it cites. | |
| const parsed = safeParseTriggerUri(evidence.uri); | |
| if (parsed.success && parsed.data.kind !== evidence.kind) { | |
| ctx.addIssue({ | |
| code: z.ZodIssueCode.custom, | |
| path: ["kind"], | |
| message: `kind "${evidence.kind}" does not match the uri's kind "${parsed.data.kind}".`, | |
| }); | |
| } | |
| }); |
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 1060fc18-ba04-495e-8289-4498890ecfe7
⛔ Files ignored due to path filters (1)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (210)
.server-changes/dashboard-agent-first-turn-error.md.server-changes/dashboard-agent-investigate.md.server-changes/dashboard-agent-watch-alerts.md.server-changes/dashboard-agent-watches.md.server-changes/queue-metrics-api.md.server-changes/remove-header-docs-buttons.mdapps/webapp/.gitignoreapps/webapp/app/components/dashboard-agent/AgentChart.tsxapps/webapp/app/components/dashboard-agent/DashboardAgent.tsxapps/webapp/app/components/dashboard-agent/DashboardAgentChat.tsxapps/webapp/app/components/dashboard-agent/DashboardAgentComposer.tsxapps/webapp/app/components/dashboard-agent/DashboardAgentContextBanner.tsxapps/webapp/app/components/dashboard-agent/DashboardAgentDraft.tsxapps/webapp/app/components/dashboard-agent/DashboardAgentHeader.tsxapps/webapp/app/components/dashboard-agent/DashboardAgentHistory.tsxapps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsxapps/webapp/app/components/dashboard-agent/DashboardAgentPanel.tsxapps/webapp/app/components/dashboard-agent/DashboardAgentSuggestedPrompts.tsxapps/webapp/app/components/dashboard-agent/InvestigateButton.tsxapps/webapp/app/components/dashboard-agent/InvestigationCard.test.tsapps/webapp/app/components/dashboard-agent/InvestigationCard.tsxapps/webapp/app/components/dashboard-agent/ReportView.test.tsapps/webapp/app/components/dashboard-agent/ReportView.tsxapps/webapp/app/components/dashboard-agent/RunDiagnosisCard.tsxapps/webapp/app/components/dashboard-agent/WakeBanner.tsxapps/webapp/app/components/dashboard-agent/WatchChips.tsxapps/webapp/app/components/dashboard-agent/WatchWakeToast.tsxapps/webapp/app/components/dashboard-agent/agent-badges.tsxapps/webapp/app/components/dashboard-agent/chat-layout.test.tsapps/webapp/app/components/dashboard-agent/chat-layout.tsxapps/webapp/app/components/dashboard-agent/dashboardAgentLauncher.tsxapps/webapp/app/components/dashboard-agent/demo/components/DemoChartCard.tsxapps/webapp/app/components/dashboard-agent/demo/components/DemoIntentBubble.tsxapps/webapp/app/components/dashboard-agent/demo/components/DemoInvestigationCard.tsxapps/webapp/app/components/dashboard-agent/demo/components/DemoReportCard.tsxapps/webapp/app/components/dashboard-agent/demo/components/DemoSuggestedPromptsRow.tsxapps/webapp/app/components/dashboard-agent/demo/components/DemoWatchChips.tsxapps/webapp/app/components/dashboard-agent/demo/demo-chats.tsapps/webapp/app/components/dashboard-agent/demo/demo.test.tsapps/webapp/app/components/dashboard-agent/demo/fixtures/blocks.tsapps/webapp/app/components/dashboard-agent/demo/fixtures/chart.tsapps/webapp/app/components/dashboard-agent/demo/fixtures/index.tsapps/webapp/app/components/dashboard-agent/demo/fixtures/intents.tsapps/webapp/app/components/dashboard-agent/demo/fixtures/investigation.tsapps/webapp/app/components/dashboard-agent/demo/fixtures/messages.tsapps/webapp/app/components/dashboard-agent/demo/fixtures/page-context.tsapps/webapp/app/components/dashboard-agent/demo/fixtures/reports.tsapps/webapp/app/components/dashboard-agent/demo/fixtures/watches.tsapps/webapp/app/components/dashboard-agent/demo/ids.tsapps/webapp/app/components/dashboard-agent/demo/index.tsapps/webapp/app/components/dashboard-agent/investigate-prompts.test.tsapps/webapp/app/components/dashboard-agent/investigate-prompts.tsapps/webapp/app/components/dashboard-agent/list-row.tsxapps/webapp/app/components/dashboard-agent/message-order.test.tsapps/webapp/app/components/dashboard-agent/message-order.tsapps/webapp/app/components/dashboard-agent/navigate-target.test.tsapps/webapp/app/components/dashboard-agent/navigate-target.tsapps/webapp/app/components/dashboard-agent/page-context-types.tsapps/webapp/app/components/dashboard-agent/page-label.test.tsapps/webapp/app/components/dashboard-agent/page-label.tsapps/webapp/app/components/dashboard-agent/progress-line.test.tsapps/webapp/app/components/dashboard-agent/progress-line.tsapps/webapp/app/components/dashboard-agent/report-block-adapter.test.tsapps/webapp/app/components/dashboard-agent/report-block-adapter.tsapps/webapp/app/components/dashboard-agent/report-sparkline.tsxapps/webapp/app/components/dashboard-agent/run-id.test.tsapps/webapp/app/components/dashboard-agent/run-id.tsapps/webapp/app/components/dashboard-agent/suggested-prompts/dismissal.tsapps/webapp/app/components/dashboard-agent/suggested-prompts/index.tsapps/webapp/app/components/dashboard-agent/suggested-prompts/page-mappers.test.tsapps/webapp/app/components/dashboard-agent/suggested-prompts/page-mappers.tsapps/webapp/app/components/dashboard-agent/suggested-prompts/promoted.test.tsapps/webapp/app/components/dashboard-agent/suggested-prompts/promoted.tsapps/webapp/app/components/dashboard-agent/suggested-prompts/promotedPrompt.server.tsapps/webapp/app/components/dashboard-agent/suggested-prompts/registry.tsapps/webapp/app/components/dashboard-agent/suggested-prompts/resolver.test.tsapps/webapp/app/components/dashboard-agent/suggested-prompts/resolver.tsapps/webapp/app/components/dashboard-agent/tool-labels.test.tsapps/webapp/app/components/dashboard-agent/tool-labels.tsapps/webapp/app/components/dashboard-agent/useTranscriptAutoScroll.tsapps/webapp/app/components/dashboard-agent/view-blocks.test.tsapps/webapp/app/components/dashboard-agent/view-blocks.tsapps/webapp/app/components/dashboard-agent/view-catalog.tsxapps/webapp/app/components/dashboard-agent/watch-chips.test.tsapps/webapp/app/components/dashboard-agent/watch-chips.tsapps/webapp/app/components/metrics/MiniLineChart.tsxapps/webapp/app/components/primitives/Callout.tsxapps/webapp/app/components/runs/v3/agent/AgentMessageView.tsxapps/webapp/app/hooks/useAgentPageContext.tsapps/webapp/app/presenters/v3/ApiAlertChannelPresenter.server.tsapps/webapp/app/presenters/v3/reports/health/health-messages.tsapps/webapp/app/presenters/v3/reports/health/health.tsapps/webapp/app/presenters/v3/waitingRun/waitingRunDiagnosis.server.tsapps/webapp/app/presenters/v3/waitingRun/waitingRunDiagnosis.tsapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam._index/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.agents.$agentParam/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.alerts.new/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.alerts/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.apikeys/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.batches/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.branches/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.bulk-actions/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.deployments/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.dev-branches/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.environment-variables/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.errors.$fingerprint/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.limits/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.prompts._index/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.runs.$runParam/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.runs._index/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.sessions.$sessionParam/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.sessions._index/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.test/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.waitpoints.tokens/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.settings.private-connections._index/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.settings.private-connections.new/route.tsxapps/webapp/app/routes/account.tokens/route.tsxapps/webapp/app/routes/api.v1.dashboard-agent.alerts.$channelId.tsapps/webapp/app/routes/api.v1.dashboard-agent.alerts.tsapps/webapp/app/routes/api.v1.dashboard-agent.watches.$watchId.check.tsapps/webapp/app/routes/api.v1.dashboard-agent.watches.$watchId.fired.tsapps/webapp/app/routes/api.v1.dashboard-agent.watches.tsapps/webapp/app/routes/api.v1.projects.$projectRef.$env.jwt.tsapps/webapp/app/routes/api.v1.projects.$projectRef.$env.repo.snapshot.tsapps/webapp/app/routes/api.v1.projects.$projectRef.$env.runs.$runId.commit.tsapps/webapp/app/routes/api.v1.projects.$projectRef.$env.runs.$runId.waiting.tsapps/webapp/app/routes/api.v1.projects.$projectRef.$env.workers.$tagName.tsapps/webapp/app/routes/api.v1.queues.$queueParam.metrics.tsapps/webapp/app/routes/resources.dashboard-agent.alerts.$channelId.unsubscribe.tsxapps/webapp/app/routes/resources.orgs.$organizationSlug.projects.$projectParam.env.$envParam.dashboard-agent.in.$.tsapps/webapp/app/routes/resources.orgs.$organizationSlug.projects.$projectParam.env.$envParam.dashboard-agent.tsapps/webapp/app/routes/resources.orgs.$organizationSlug.projects.$projectParam.env.$envParam.runs.$runParam.spans.$spanParam/route.tsxapps/webapp/app/routes/storybook.agent-ui/manifest.tsapps/webapp/app/routes/storybook.agent-ui/route.tsxapps/webapp/app/routes/storybook.callout/route.tsxapps/webapp/app/services/dashboardAgentAlertContext.server.tsapps/webapp/app/services/dashboardAgentAlertUnsubscribeToken.server.tsapps/webapp/app/services/dashboardAgentHeadStart.server.tsapps/webapp/app/services/dashboardAgentWatchAlerts.server.tsapps/webapp/app/services/dashboardAgentWatchChecks.server.tsapps/webapp/app/services/dashboardAgentWatchChecks.tsapps/webapp/app/services/dashboardAgentWatchToken.server.tsapps/webapp/app/services/dashboardAgentWatches.server.tsapps/webapp/app/services/resolveTriggerUri.server.tsapps/webapp/app/services/uatRoutePreamble.server.tsapps/webapp/app/utils/handle.tsapps/webapp/app/v3/alertsWorker.server.tsapps/webapp/app/v3/featureFlags.tsapps/webapp/app/v3/services/alerts/deliverAlert.server.tsapps/webapp/app/v3/services/alerts/deliverDashboardAgentWatchAlert.server.tsapps/webapp/package.jsonapps/webapp/scripts/agent-ui-screenshots.tsapps/webapp/seed-agent-examples-chats.mtsapps/webapp/seed-agent-examples.mtsapps/webapp/seed-queue-metrics.mtsapps/webapp/test/dashboardAgentHeadStart.test.tsapps/webapp/test/dashboardAgentRoutes.test.tsapps/webapp/test/dashboardAgentWatchChecks.test.tsapps/webapp/test/dashboardAgentWatchToken.test.tsapps/webapp/test/dashboardAgentWatches.test.tsapps/webapp/test/reportHealth.test.tsapps/webapp/test/resolveTriggerUri.test.tsapps/webapp/test/seedAgentExamplesChats.test.tsapps/webapp/test/waitingRunDiagnosis.test.tsapps/webapp/vitest.config.tsinternal-packages/dashboard-agent-contracts/package.jsoninternal-packages/dashboard-agent-contracts/src/blocks.test.tsinternal-packages/dashboard-agent-contracts/src/blocks.tsinternal-packages/dashboard-agent-contracts/src/contracts.test.tsinternal-packages/dashboard-agent-contracts/src/evidence.tsinternal-packages/dashboard-agent-contracts/src/index.tsinternal-packages/dashboard-agent-contracts/src/intent.tsinternal-packages/dashboard-agent-contracts/src/page-context.tsinternal-packages/dashboard-agent-contracts/src/run-filters.tsinternal-packages/dashboard-agent-contracts/src/suggested-prompts.tsinternal-packages/dashboard-agent-contracts/src/trigger-uri.test.tsinternal-packages/dashboard-agent-contracts/src/trigger-uri.tsinternal-packages/dashboard-agent-contracts/src/watch.test.tsinternal-packages/dashboard-agent-contracts/src/watch.tsinternal-packages/dashboard-agent-contracts/tsconfig.jsoninternal-packages/dashboard-agent-contracts/vitest.config.tsinternal-packages/dashboard-agent-db/README.mdinternal-packages/dashboard-agent-db/drizzle/0002_luxuriant_king_cobra.sqlinternal-packages/dashboard-agent-db/drizzle/0003_famous_champions.sqlinternal-packages/dashboard-agent-db/drizzle/meta/0002_snapshot.jsoninternal-packages/dashboard-agent-db/drizzle/meta/0003_snapshot.jsoninternal-packages/dashboard-agent-db/drizzle/meta/_journal.jsoninternal-packages/dashboard-agent-db/package.jsoninternal-packages/dashboard-agent-db/src/ids.tsinternal-packages/dashboard-agent-db/src/index.tsinternal-packages/dashboard-agent-db/src/queries.tsinternal-packages/dashboard-agent-db/src/schema.tsinternal-packages/dashboard-agent/GUIDEBOOK.mdinternal-packages/dashboard-agent/PLAYBOOK.mdinternal-packages/dashboard-agent/VERDICTS.mdinternal-packages/dashboard-agent/package.jsoninternal-packages/dashboard-agent/src/dashboard-agent.eval.tsinternal-packages/dashboard-agent/src/dashboard-agent.test.tsinternal-packages/dashboard-agent/src/dashboard-agent.tsinternal-packages/dashboard-agent/src/index.tsinternal-packages/dashboard-agent/src/tool-schemas.tsinternal-packages/dashboard-agent/src/tools.tsinternal-packages/dashboard-agent/src/watch-tick.test.tsinternal-packages/dashboard-agent/src/watch-tick.tsinternal-packages/dashboard-agent/vitest.eval.config.tsinternal-packages/database/prisma/migrations/20260729120000_add_dashboard_agent_watch_alert_type/migration.sqlinternal-packages/database/prisma/schema.prismainternal-packages/emails/emails/alert-dashboard-agent-watch.tsxinternal-packages/emails/src/index.tsx
💤 Files with no reviewable changes (1)
- apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.branches/route.tsx
🚧 Files skipped from review as they are similar to previous changes (189)
- .server-changes/dashboard-agent-watches.md
- apps/webapp/app/components/dashboard-agent/investigate-prompts.test.ts
- .server-changes/dashboard-agent-first-turn-error.md
- .server-changes/queue-metrics-api.md
- apps/webapp/app/routes/storybook.callout/route.tsx
- .server-changes/remove-header-docs-buttons.md
- apps/webapp/app/components/dashboard-agent/InvestigationCard.test.ts
- apps/webapp/app/components/dashboard-agent/progress-line.test.ts
- apps/webapp/app/components/dashboard-agent/tool-labels.ts
- internal-packages/dashboard-agent-db/drizzle/0003_famous_champions.sql
- apps/webapp/app/components/dashboard-agent/suggested-prompts/promoted.ts
- apps/webapp/app/components/dashboard-agent/page-context-types.ts
- internal-packages/dashboard-agent-db/src/ids.ts
- apps/webapp/app/components/dashboard-agent/page-label.test.ts
- .server-changes/dashboard-agent-investigate.md
- internal-packages/dashboard-agent-db/src/index.ts
- apps/webapp/app/components/dashboard-agent/demo/components/DemoWatchChips.tsx
- internal-packages/dashboard-agent-db/package.json
- apps/webapp/app/components/dashboard-agent/run-id.ts
- apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.test/route.tsx
- apps/webapp/app/components/dashboard-agent/demo/fixtures/index.ts
- internal-packages/dashboard-agent-db/drizzle/0002_luxuriant_king_cobra.sql
- apps/webapp/vitest.config.ts
- apps/webapp/app/presenters/v3/reports/health/health.ts
- apps/webapp/app/components/dashboard-agent/suggested-prompts/index.ts
- apps/webapp/.gitignore
- apps/webapp/app/components/dashboard-agent/ReportView.test.ts
- apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.waitpoints.tokens/route.tsx
- apps/webapp/app/routes/_app.orgs.$organizationSlug.settings.private-connections._index/route.tsx
- apps/webapp/app/components/dashboard-agent/message-order.test.ts
- internal-packages/dashboard-agent-contracts/src/index.ts
- apps/webapp/app/components/dashboard-agent/InvestigateButton.tsx
- apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.dev-branches/route.tsx
- .server-changes/dashboard-agent-watch-alerts.md
- apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.errors.$fingerprint/route.tsx
- internal-packages/dashboard-agent-contracts/package.json
- apps/webapp/app/services/uatRoutePreamble.server.ts
- apps/webapp/app/components/dashboard-agent/demo/fixtures/intents.ts
- internal-packages/dashboard-agent/src/index.ts
- apps/webapp/app/v3/alertsWorker.server.ts
- apps/webapp/app/hooks/useAgentPageContext.ts
- apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.alerts/route.tsx
- apps/webapp/app/components/dashboard-agent/demo/components/DemoChartCard.tsx
- apps/webapp/app/components/metrics/MiniLineChart.tsx
- internal-packages/dashboard-agent/vitest.eval.config.ts
- apps/webapp/app/components/dashboard-agent/DashboardAgentHeader.tsx
- internal-packages/dashboard-agent-contracts/tsconfig.json
- internal-packages/database/prisma/schema.prisma
- apps/webapp/app/components/dashboard-agent/tool-labels.test.ts
- apps/webapp/app/services/dashboardAgentAlertContext.server.ts
- apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.apikeys/route.tsx
- apps/webapp/app/routes/resources.orgs.$organizationSlug.projects.$projectParam.env.$envParam.runs.$runParam.spans.$spanParam/route.tsx
- apps/webapp/app/routes/api.v1.projects.$projectRef.$env.repo.snapshot.ts
- apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.bulk-actions/route.tsx
- apps/webapp/app/components/dashboard-agent/suggested-prompts/resolver.ts
- apps/webapp/app/components/dashboard-agent/suggested-prompts/dismissal.ts
- apps/webapp/app/routes/api.v1.projects.$projectRef.$env.runs.$runId.commit.ts
- apps/webapp/package.json
- apps/webapp/app/components/dashboard-agent/navigate-target.test.ts
- apps/webapp/app/routes/api.v1.projects.$projectRef.$env.workers.$tagName.ts
- apps/webapp/app/components/dashboard-agent/demo/index.ts
- internal-packages/dashboard-agent-db/drizzle/meta/_journal.json
- internal-packages/dashboard-agent-contracts/src/evidence.ts
- internal-packages/dashboard-agent-contracts/src/intent.ts
- internal-packages/dashboard-agent-contracts/src/page-context.ts
- apps/webapp/test/dashboardAgentHeadStart.test.ts
- apps/webapp/app/components/dashboard-agent/progress-line.ts
- apps/webapp/app/components/dashboard-agent/view-blocks.ts
- apps/webapp/app/components/dashboard-agent/WakeBanner.tsx
- apps/webapp/app/components/dashboard-agent/demo/components/DemoSuggestedPromptsRow.tsx
- apps/webapp/app/components/dashboard-agent/DashboardAgentDraft.tsx
- apps/webapp/app/components/primitives/Callout.tsx
- apps/webapp/app/routes/account.tokens/route.tsx
- apps/webapp/app/components/dashboard-agent/navigate-target.ts
- apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.sessions._index/route.tsx
- apps/webapp/app/components/dashboard-agent/investigate-prompts.ts
- apps/webapp/test/dashboardAgentWatchToken.test.ts
- apps/webapp/app/components/dashboard-agent/demo/components/DemoIntentBubble.tsx
- apps/webapp/app/routes/api.v1.dashboard-agent.alerts.$channelId.ts
- apps/webapp/app/utils/handle.ts
- apps/webapp/app/components/dashboard-agent/demo/components/DemoReportCard.tsx
- apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.deployments/route.tsx
- internal-packages/dashboard-agent-contracts/vitest.config.ts
- apps/webapp/app/components/dashboard-agent/watch-chips.test.ts
- apps/webapp/app/components/dashboard-agent/demo/fixtures/reports.ts
- apps/webapp/app/components/dashboard-agent/demo/demo-chats.ts
- internal-packages/dashboard-agent/package.json
- apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.batches/route.tsx
- internal-packages/dashboard-agent-db/README.md
- apps/webapp/test/reportHealth.test.ts
- apps/webapp/app/components/dashboard-agent/DashboardAgentComposer.tsx
- apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.sessions.$sessionParam/route.tsx
- apps/webapp/test/resolveTriggerUri.test.ts
- apps/webapp/app/routes/api.v1.dashboard-agent.watches.ts
- apps/webapp/app/components/dashboard-agent/demo/fixtures/chart.ts
- apps/webapp/app/components/runs/v3/agent/AgentMessageView.tsx
- internal-packages/emails/src/index.tsx
- apps/webapp/app/components/dashboard-agent/dashboardAgentLauncher.tsx
- internal-packages/dashboard-agent-contracts/src/run-filters.ts
- apps/webapp/app/presenters/v3/ApiAlertChannelPresenter.server.ts
- apps/webapp/app/components/dashboard-agent/suggested-prompts/promoted.test.ts
- apps/webapp/app/presenters/v3/reports/health/health-messages.ts
- apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.alerts.new/route.tsx
- internal-packages/dashboard-agent-contracts/src/trigger-uri.test.ts
- apps/webapp/app/components/dashboard-agent/agent-badges.tsx
- apps/webapp/app/services/dashboardAgentAlertUnsubscribeToken.server.ts
- apps/webapp/app/services/dashboardAgentWatchToken.server.ts
- apps/webapp/app/components/dashboard-agent/suggested-prompts/page-mappers.ts
- apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.prompts._index/route.tsx
- apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.environment-variables/route.tsx
- internal-packages/dashboard-agent-contracts/src/watch.test.ts
- apps/webapp/app/components/dashboard-agent/WatchChips.tsx
- apps/webapp/app/routes/api.v1.projects.$projectRef.$env.jwt.ts
- apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam/route.tsx
- internal-packages/dashboard-agent-contracts/src/trigger-uri.ts
- internal-packages/dashboard-agent-contracts/src/suggested-prompts.ts
- internal-packages/emails/emails/alert-dashboard-agent-watch.tsx
- apps/webapp/app/components/dashboard-agent/useTranscriptAutoScroll.ts
- apps/webapp/app/components/dashboard-agent/report-block-adapter.test.ts
- apps/webapp/app/components/dashboard-agent/view-catalog.tsx
- apps/webapp/app/components/dashboard-agent/watch-chips.ts
- apps/webapp/app/components/dashboard-agent/view-blocks.test.ts
- apps/webapp/app/components/dashboard-agent/demo/demo.test.ts
- apps/webapp/app/routes/api.v1.dashboard-agent.alerts.ts
- apps/webapp/app/components/dashboard-agent/list-row.tsx
- apps/webapp/app/components/dashboard-agent/suggested-prompts/promotedPrompt.server.ts
- apps/webapp/app/components/dashboard-agent/page-label.ts
- apps/webapp/app/components/dashboard-agent/run-id.test.ts
- apps/webapp/app/routes/resources.orgs.$organizationSlug.projects.$projectParam.env.$envParam.dashboard-agent.ts
- apps/webapp/app/services/dashboardAgentWatchChecks.server.ts
- apps/webapp/seed-agent-examples-chats.mts
- apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam._index/route.tsx
- apps/webapp/app/components/dashboard-agent/demo/fixtures/messages.ts
- apps/webapp/app/v3/featureFlags.ts
- internal-packages/dashboard-agent-contracts/src/watch.ts
- apps/webapp/app/services/dashboardAgentWatchAlerts.server.ts
- apps/webapp/app/components/dashboard-agent/suggested-prompts/registry.ts
- apps/webapp/app/routes/api.v1.projects.$projectRef.$env.runs.$runId.waiting.ts
- apps/webapp/app/components/dashboard-agent/chat-layout.test.ts
- apps/webapp/app/routes/resources.orgs.$organizationSlug.projects.$projectParam.env.$envParam.dashboard-agent.in.$.ts
- apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.agents.$agentParam/route.tsx
- apps/webapp/app/components/dashboard-agent/demo/fixtures/watches.ts
- apps/webapp/app/services/dashboardAgentWatches.server.ts
- apps/webapp/app/services/dashboardAgentHeadStart.server.ts
- apps/webapp/app/components/dashboard-agent/suggested-prompts/page-mappers.test.ts
- apps/webapp/test/dashboardAgentWatchChecks.test.ts
- apps/webapp/scripts/agent-ui-screenshots.ts
- internal-packages/dashboard-agent/src/watch-tick.test.ts
- apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.limits/route.tsx
- apps/webapp/app/v3/services/alerts/deliverDashboardAgentWatchAlert.server.ts
- apps/webapp/test/dashboardAgentRoutes.test.ts
- apps/webapp/app/components/dashboard-agent/report-block-adapter.ts
- apps/webapp/test/seedAgentExamplesChats.test.ts
- apps/webapp/test/dashboardAgentWatches.test.ts
- apps/webapp/app/components/dashboard-agent/RunDiagnosisCard.tsx
- apps/webapp/app/components/dashboard-agent/WatchWakeToast.tsx
- apps/webapp/app/components/dashboard-agent/message-order.ts
- apps/webapp/app/components/dashboard-agent/demo/fixtures/page-context.ts
- apps/webapp/app/routes/resources.dashboard-agent.alerts.$channelId.unsubscribe.tsx
- apps/webapp/app/components/dashboard-agent/chat-layout.tsx
- apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.runs._index/route.tsx
- apps/webapp/app/components/dashboard-agent/InvestigationCard.tsx
- internal-packages/dashboard-agent/src/dashboard-agent.ts
- apps/webapp/app/components/dashboard-agent/suggested-prompts/resolver.test.ts
- apps/webapp/app/presenters/v3/waitingRun/waitingRunDiagnosis.server.ts
- apps/webapp/app/components/dashboard-agent/demo/fixtures/investigation.ts
- apps/webapp/seed-agent-examples.mts
- apps/webapp/app/components/dashboard-agent/DashboardAgentChat.tsx
- apps/webapp/app/routes/api.v1.dashboard-agent.watches.$watchId.check.ts
- apps/webapp/app/components/dashboard-agent/demo/fixtures/blocks.ts
- apps/webapp/app/components/dashboard-agent/ReportView.tsx
- apps/webapp/app/routes/api.v1.dashboard-agent.watches.$watchId.fired.ts
- apps/webapp/app/routes/_app.orgs.$organizationSlug.settings.private-connections.new/route.tsx
- apps/webapp/app/components/dashboard-agent/demo/components/DemoInvestigationCard.tsx
- internal-packages/dashboard-agent-db/drizzle/meta/0002_snapshot.json
- apps/webapp/app/services/resolveTriggerUri.server.ts
- internal-packages/dashboard-agent-db/drizzle/meta/0003_snapshot.json
- internal-packages/dashboard-agent/src/dashboard-agent.test.ts
- internal-packages/dashboard-agent/src/dashboard-agent.eval.ts
- apps/webapp/app/components/dashboard-agent/DashboardAgent.tsx
- internal-packages/dashboard-agent/src/watch-tick.ts
- apps/webapp/app/components/dashboard-agent/DashboardAgentHistory.tsx
- apps/webapp/test/waitingRunDiagnosis.test.ts
- apps/webapp/app/routes/storybook.agent-ui/route.tsx
- internal-packages/dashboard-agent/src/tool-schemas.ts
- apps/webapp/app/services/dashboardAgentWatchChecks.ts
- internal-packages/dashboard-agent/src/tools.ts
- internal-packages/dashboard-agent-db/src/queries.ts
- apps/webapp/app/routes/api.v1.queues.$queueParam.metrics.ts
| if (run.queuedAt) { | ||
| // Canonical queue wait = startedAt - queuedAt; for a run that hasn't started, now - queuedAt. | ||
| const end = run.startedAt ?? now; | ||
| const ms = Math.max(0, end.getTime() - run.queuedAt.getTime()); | ||
| waitingLabel = `queued for ${formatMs(ms)}`; | ||
| waitingBasis = "queued_at"; | ||
| } else if (run.delayUntil && run.delayUntil.getTime() > now.getTime()) { | ||
| // A delayed run isn't in the queue yet — this is a schedule, NOT queue latency. | ||
| waitingLabel = `scheduled to start at ${run.delayUntil.toISOString()}`; | ||
| waitingBasis = "delay_until"; | ||
| } else { | ||
| // No queuedAt to measure from. Report creation age and SAY that's what it is. | ||
| const ms = Math.max(0, (run.startedAt ?? now).getTime() - run.createdAt.getTime()); | ||
| waitingLabel = `time from creation: ${formatMs(ms)}`; | ||
| waitingBasis = "created_at"; | ||
| } |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
waitingLabel can misreport an overdue delay as "time from creation".
When delayUntil has already elapsed but the run hasn't been re-enqueued yet (queuedAt still null), the branch at Line 237 is skipped (since delayUntil.getTime() > now.getTime() is false) and control falls to the "time from creation" branch. This measures from createdAt, which can be well before delayUntil — overstating how long the run has effectively been stuck versus its actual overdue-delay wait.
🐛 Proposed fix
if (run.queuedAt) {
// Canonical queue wait = startedAt - queuedAt; for a run that hasn't started, now - queuedAt.
const end = run.startedAt ?? now;
const ms = Math.max(0, end.getTime() - run.queuedAt.getTime());
waitingLabel = `queued for ${formatMs(ms)}`;
waitingBasis = "queued_at";
} else if (run.delayUntil && run.delayUntil.getTime() > now.getTime()) {
// A delayed run isn't in the queue yet — this is a schedule, NOT queue latency.
waitingLabel = `scheduled to start at ${run.delayUntil.toISOString()}`;
waitingBasis = "delay_until";
+ } else if (run.delayUntil) {
+ // Delay has elapsed but the run hasn't been re-enqueued yet — measure from delayUntil,
+ // not createdAt, so a stale schedule window isn't blamed on this wait.
+ const ms = Math.max(0, (run.startedAt ?? now).getTime() - run.delayUntil.getTime());
+ waitingLabel = `overdue by ${formatMs(ms)}`;
+ waitingBasis = "delay_until";
} else {
// No queuedAt to measure from. Report creation age and SAY that's what it is.
const ms = Math.max(0, (run.startedAt ?? now).getTime() - run.createdAt.getTime());
waitingLabel = `time from creation: ${formatMs(ms)}`;
waitingBasis = "created_at";
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| if (run.queuedAt) { | |
| // Canonical queue wait = startedAt - queuedAt; for a run that hasn't started, now - queuedAt. | |
| const end = run.startedAt ?? now; | |
| const ms = Math.max(0, end.getTime() - run.queuedAt.getTime()); | |
| waitingLabel = `queued for ${formatMs(ms)}`; | |
| waitingBasis = "queued_at"; | |
| } else if (run.delayUntil && run.delayUntil.getTime() > now.getTime()) { | |
| // A delayed run isn't in the queue yet — this is a schedule, NOT queue latency. | |
| waitingLabel = `scheduled to start at ${run.delayUntil.toISOString()}`; | |
| waitingBasis = "delay_until"; | |
| } else { | |
| // No queuedAt to measure from. Report creation age and SAY that's what it is. | |
| const ms = Math.max(0, (run.startedAt ?? now).getTime() - run.createdAt.getTime()); | |
| waitingLabel = `time from creation: ${formatMs(ms)}`; | |
| waitingBasis = "created_at"; | |
| } | |
| if (run.queuedAt) { | |
| // Canonical queue wait = startedAt - queuedAt; for a run that hasn't started, now - queuedAt. | |
| const end = run.startedAt ?? now; | |
| const ms = Math.max(0, end.getTime() - run.queuedAt.getTime()); | |
| waitingLabel = `queued for ${formatMs(ms)}`; | |
| waitingBasis = "queued_at"; | |
| } else if (run.delayUntil && run.delayUntil.getTime() > now.getTime()) { | |
| // A delayed run isn't in the queue yet — this is a schedule, NOT queue latency. | |
| waitingLabel = `scheduled to start at ${run.delayUntil.toISOString()}`; | |
| waitingBasis = "delay_until"; | |
| } else if (run.delayUntil) { | |
| // Delay has elapsed but the run hasn't been re-enqueued yet — measure from delayUntil, | |
| // not createdAt, so a stale schedule window isn't blamed on this wait. | |
| const ms = Math.max(0, (run.startedAt ?? now).getTime() - run.delayUntil.getTime()); | |
| waitingLabel = `overdue by ${formatMs(ms)}`; | |
| waitingBasis = "delay_until"; | |
| } else { | |
| // No queuedAt to measure from. Report creation age and SAY that's what it is. | |
| const ms = Math.max(0, (run.startedAt ?? now).getTime() - run.createdAt.getTime()); | |
| waitingLabel = `time from creation: ${formatMs(ms)}`; | |
| waitingBasis = "created_at"; | |
| } |
… is one sentence Latest-wins now applies across the whole transcript, not just within one tool call — the in_progress working copy disappears when the verdict revision renders. The prompt bans list-shaped prose after the verdict card: everything list-shaped belongs on the card.
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
internal-packages/dashboard-agent/src/tool-schemas.ts (1)
547-559: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick winAlign the capability instructions with the new mutating tools.
The prompt now exposes
schedule_watch,create_alert, anddelete_alert, but it still describes the toolset as read-only and later says the agent cannot change anything. This contradiction can make the agent refuse supported watch/alert actions or incorrectly direct users to the dashboard. Update the blanket capability text to distinguish read-only data tools from these explicitly authorized mutations.
🧹 Nitpick comments (1)
apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx (1)
351-368: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick winMemoize the transcript-derived winner map.
Line 357 creates a new
Mapon every render, and Line 368 passes it tomemoized turns; activity-only updates therefore rerender the entire transcript and rescan all parts. Memoizestrippedand its winners frommessages.Proposed change
- const stripped = messages.map(stripStepParts); - - const investigationWinners = winningInvestigationOccurrences(stripped); + const { stripped, investigationWinners } = useMemo(() => { + const stripped = messages.map(stripStepParts); + return { + stripped, + investigationWinners: winningInvestigationOccurrences(stripped), + }; + }, [messages]);As per coding guidelines,
useMemois appropriate for expensive derived data and stable references required by dependency arrays.Source: Coding guidelines
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: ae8860fd-cece-44f8-b032-c969b4234488
📒 Files selected for processing (2)
apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsxinternal-packages/dashboard-agent/src/tool-schemas.ts
📜 Review details
⏰ Context from checks skipped due to timeout. (33)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (12, 12)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (11, 12)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (7, 12)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (6, 12)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (4, 12)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (5, 12)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (1, 12)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (8, 12)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (10, 12)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (9, 12)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (3, 12)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (2, 12)
- GitHub Check: sdk-compat / Node.js 22.23 (warp-ubuntu-latest-x64-4x)
- GitHub Check: sdk-compat / Node.js 24.18 (warp-ubuntu-latest-x64-4x)
- GitHub Check: sdk-compat / Bun Runtime
- GitHub Check: sdk-compat / Node.js 26.4 (warp-ubuntu-latest-x64-4x)
- GitHub Check: sdk-compat / Node.js 20.20 (warp-ubuntu-latest-x64-4x)
- GitHub Check: e2e / 🧪 CLI v3 tests (warp-ubuntu-latest-x64-4x - pnpm)
- GitHub Check: e2e / 🧪 CLI v3 tests (warp-windows-latest-x64-8x - pnpm)
- GitHub Check: typecheck / typecheck
- GitHub Check: e2e / 🧪 CLI v3 tests (warp-ubuntu-latest-x64-4x - npm)
- GitHub Check: e2e / 🧪 CLI v3 tests (warp-windows-latest-x64-8x - npm)
- GitHub Check: packages / 🧪 Unit Tests: Packages (2, 3)
- GitHub Check: packages / 🧪 Unit Tests: Packages (3, 3)
- GitHub Check: packages / 🧪 Unit Tests: Packages (1, 3)
- GitHub Check: sdk-compat / Cloudflare Workers
- GitHub Check: sdk-compat / Deno Runtime
- GitHub Check: runops-guard / runops-guard
- GitHub Check: internal / 🧪 Unit Tests: Internal
- GitHub Check: e2e-webapp / 🧪 E2E Tests: Webapp
- GitHub Check: code-quality / code-quality
- GitHub Check: 🛡️ E2E Auth Tests (full)
- GitHub Check: Analyze (javascript-typescript)
🧰 Additional context used
📓 Path-based instructions (8)
**/*.{ts,tsx}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
**/*.{ts,tsx}: Use types over interfaces for TypeScript
Avoid using enums; prefer string unions or const objects instead
**/*.{ts,tsx}: Prefer static imports over dynamicimport(); use dynamic imports only for unresolvable circular dependencies, genuine performance code splitting, or conditional runtime loading.
Import Trigger.dev tasks from@trigger.dev/sdk; never use@trigger.dev/sdk/v3or deprecatedclient.defineJob.
Add agentcrumbs while writing code using approved namespaces; mark lines with//@Crumbsor blocks with `// `#region` `@crumbs, and strip them before merging.
Files:
apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsxinternal-packages/dashboard-agent/src/tool-schemas.ts
{packages/core,apps/webapp}/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Use zod for validation in packages/core and apps/webapp
Files:
apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx
**/*.{ts,tsx,js,jsx}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Use function declarations instead of default exports
Files:
apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsxinternal-packages/dashboard-agent/src/tool-schemas.ts
apps/webapp/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/webapp.mdc)
apps/webapp/**/*.{ts,tsx}: Access environment variables through theenvexport ofenv.server.tsinstead of directly accessingprocess.env
Use subpath exports from@trigger.dev/corepackage instead of importing from the root@trigger.dev/corepathDo not reintroduce the removed v1 execution path;
RunEngineVersion.V1branches may only reject or finalize gracefully so v3 clients receive a clean 4xx, never a 5xx.
Files:
apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx
apps/**/*.{ts,tsx}
📄 CodeRabbit inference engine (AGENTS.md)
For apps, use
typecheckfor verification and never usebuildas the correctness check.
Files:
apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx
apps/webapp/app/**/*.{ts,tsx}
📄 CodeRabbit inference engine (apps/webapp/CLAUDE.md)
apps/webapp/app/**/*.{ts,tsx}: For dashboard changes, visually verify the running Remix app with Chrome DevTools MCP, using snapshots, screenshots, interaction, and console-message checks as appropriate.
UseuseCallbackanduseMemoonly for context provider values, expensive derived data used as a dependency, or stable references required by dependency arrays; do not wrap ordinary event handlers or trivial computations.
Use named constants for sentinel or placeholder values instead of scattering raw string literals across comparisons.
Files:
apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx
**/*.ts
📄 CodeRabbit inference engine (.cursor/rules/otel-metrics.mdc)
**/*.ts: When creating or editing OTEL metrics (counters, histograms, gauges), ensure metric attributes have low cardinality by using only enums, booleans, bounded error codes, or bounded shard IDs
Do not use high-cardinality attributes in OTEL metrics such as UUIDs/IDs (envId, userId, runId, projectId, organizationId), unbounded integers (itemCount, batchSize, retryCount), timestamps (createdAt, startTime), or free-form strings (errorMessage, taskName, queueName)
When exporting OTEL metrics via OTLP to Prometheus, be aware that the exporter automatically adds unit suffixes to metric names (e.g., 'my_duration_ms' becomes 'my_duration_ms_milliseconds', 'my_counter' becomes 'my_counter_total'). Account for these transformations when writing Grafana dashboards or Prometheus queries
Files:
internal-packages/dashboard-agent/src/tool-schemas.ts
internal-packages/**/*.{ts,tsx}
📄 CodeRabbit inference engine (AGENTS.md)
For internal packages, use
typecheckfor verification and never usebuildas the correctness check.
Files:
internal-packages/dashboard-agent/src/tool-schemas.ts
🧠 Learnings (18)
📚 Learning: 2026-02-11T16:37:32.429Z
Learnt from: matt-aitken
Repo: triggerdotdev/trigger.dev PR: 3019
File: apps/webapp/app/components/primitives/charts/Card.tsx:26-30
Timestamp: 2026-02-11T16:37:32.429Z
Learning: In projects using react-grid-layout, avoid relying on drag-handle class to imply draggability. Ensure drag-handle elements only affect dragging when the parent grid item is configured draggable in the layout; conditionally apply cursor styles based on the draggable prop. This improves correctness and accessibility.
Applied to files:
apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx
📚 Learning: 2026-07-28T21:57:20.061Z
Learnt from: samejr
Repo: triggerdotdev/trigger.dev PR: 4411
File: apps/webapp/app/routes/_app.orgs.$organizationSlug.settings.team/route.tsx:818-843
Timestamp: 2026-07-28T21:57:20.061Z
Learning: When using Radix UI `DialogClose` with `asChild` (e.g., Trigger.dev dashboard components), note that it injects `type="button"` into its child via `Slot`. If the child is a local `Button` that forwards its `type` prop to the native `<button>`, then placing it inside a `<form>` will *not* submit unless you explicitly set `type="submit"` (or otherwise override the injected type / wire up submission behavior). Review form actions to ensure the intended submit vs non-submit behavior is preserved.
Applied to files:
apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx
📚 Learning: 2026-03-22T13:26:12.060Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 3244
File: apps/webapp/app/components/code/TextEditor.tsx:81-86
Timestamp: 2026-03-22T13:26:12.060Z
Learning: In the triggerdotdev/trigger.dev codebase, do not flag `navigator.clipboard.writeText(...)` calls for `missing-await`/`unhandled-promise` issues. These clipboard writes are intentionally invoked without `await` and without `catch` handlers across the project; keep that behavior consistent when reviewing TypeScript/TSX files (e.g., usages like in `apps/webapp/app/components/code/TextEditor.tsx`).
Applied to files:
apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsxinternal-packages/dashboard-agent/src/tool-schemas.ts
📚 Learning: 2026-03-22T19:24:14.403Z
Learnt from: matt-aitken
Repo: triggerdotdev/trigger.dev PR: 3187
File: apps/webapp/app/v3/services/alerts/deliverErrorGroupAlert.server.ts:200-204
Timestamp: 2026-03-22T19:24:14.403Z
Learning: In the triggerdotdev/trigger.dev codebase, webhook URLs are not expected to contain embedded credentials/secrets (e.g., fields like `ProjectAlertWebhookProperties` should only hold credential-free webhook endpoints). During code review, if you see logging or inclusion of raw webhook URLs in error messages, do not automatically treat it as a credential-leak/secrets-in-logs issue by default—first verify the URL does not contain embedded credentials (for example, no username/password in the URL, no obvious secret/token query params or fragments). If the URL is credential-free per this project’s conventions, allow the logging.
Applied to files:
apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsxinternal-packages/dashboard-agent/src/tool-schemas.ts
📚 Learning: 2026-05-18T08:21:27.694Z
Learnt from: d-cs
Repo: triggerdotdev/trigger.dev PR: 3632
File: apps/webapp/sentry.server.ts:4-21
Timestamp: 2026-05-18T08:21:27.694Z
Learning: When handling Prisma error P1001 ("Can't reach database server") in TypeScript, don’t assume a single error shape. Prisma can surface P1001 via two different error classes/fields: `PrismaClientKnownRequestError` exposes it as `err.code === "P1001"` (common during mid-query connection drops), while `PrismaClientInitializationError` exposes it as `err.errorCode === "P1001"` (common on client startup failure). Therefore, predicates should use `err.code === "P1001" || err.errorCode === "P1001"`. Do not flag `err.code === "P1001"` as “unreachable/never matches,” as it is expected in production.
Applied to files:
apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsxinternal-packages/dashboard-agent/src/tool-schemas.ts
📚 Learning: 2026-05-18T08:21:27.694Z
Learnt from: d-cs
Repo: triggerdotdev/trigger.dev PR: 3632
File: apps/webapp/sentry.server.ts:4-21
Timestamp: 2026-05-18T08:21:27.694Z
Learning: When handling Prisma errors for P1001 ("Can't reach database server"), do not assume it only appears under a single property name. Prisma may surface P1001 via either `PrismaClientKnownRequestError` (`err.code === "P1001"`, e.g., mid-query connection drops) or `PrismaClientInitializationError` (`err.errorCode === "P1001"`, e.g., client startup connection failure). To reliably detect the condition, check `err.code === "P1001" || err.errorCode === "P1001"`, and avoid review rules that would incorrectly flag `err.code === "P1001"` as unreachable/never-matching.
Applied to files:
apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsxinternal-packages/dashboard-agent/src/tool-schemas.ts
📚 Learning: 2026-06-13T19:53:13.759Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 3937
File: packages/trigger-sdk/skills/realtime-and-frontend/SKILL.md:258-260
Timestamp: 2026-06-13T19:53:13.759Z
Learning: When reviewing code that uses `trigger.dev/react-hooks`’s `useRealtimeRun`, preserve the call signature where the first argument is the full realtime handle object (not `handle.id`). This is intentional to maintain type-safety and is consistent with the official docs; do not suggest changing the first argument from the handle object to `handle.id`.
Applied to files:
apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsxinternal-packages/dashboard-agent/src/tool-schemas.ts
📚 Learning: 2026-06-17T17:13:49.929Z
Learnt from: matt-aitken
Repo: triggerdotdev/trigger.dev PR: 3948
File: apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.bulk-actions.$bulkActionParam/route.tsx:48-62
Timestamp: 2026-06-17T17:13:49.929Z
Learning: In triggerdotdev/trigger.dev, within `dashboardLoader`/`dashboardAction` (or similar context resolver code) whenever you resolve an organization ID from an organization slug for RBAC/enterprise authorization scope, always read from the primary Prisma client (`prisma`), not `$replica`. Using `$replica` can hit replica-lag and cause the RBAC lookup/authorization to run without the correct org scope (bypassing intended role enforcement). Implement the slug→org lookup with `prisma.organization.findFirst(...)` (or equivalent primary-client query) and add an inline comment documenting why the primary client is required (replica lag could lead to unscoped RBAC checks).
Applied to files:
apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsxinternal-packages/dashboard-agent/src/tool-schemas.ts
📚 Learning: 2026-06-23T13:04:21.413Z
Learnt from: carderne
Repo: triggerdotdev/trigger.dev PR: 4023
File: apps/webapp/app/services/upsertBranch.server.ts:14-18
Timestamp: 2026-06-23T13:04:21.413Z
Learning: In TypeScript, it’s valid to `import { type X }` and then use `typeof X` in a type-only position, e.g. `type Alias = z.infer<typeof X>`. The `type` modifier suppresses the runtime import, but the type checker still has the full exported type so `z.infer<typeof X>` can resolve correctly. In code reviews, don’t flag this as a TypeScript compile error as long as `typeof X` is used in a type context (e.g., with `z.infer`, `type` aliases, generics), not as a runtime value.
Applied to files:
apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsxinternal-packages/dashboard-agent/src/tool-schemas.ts
📚 Learning: 2026-04-16T14:21:15.229Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 3368
File: apps/webapp/app/components/logs/LogsTaskFilter.tsx:135-163
Timestamp: 2026-04-16T14:21:15.229Z
Learning: When rendering lists of task registry items in apps/webapp (e.g., <SelectItem /> rows) and using `key={item.slug}`, do not flag it as potentially non-unique. In trigger.dev’s `TaskIdentifier` table, the DB constraint `@unique([runtimeEnvironmentId, slug])` guarantees `slug` is unique within a given runtime environment, so `item.slug` is safe as the React key as long as the list is derived from that registry/constraint (and not from a legacy query that could produce duplicate slugs).
Applied to files:
apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx
📚 Learning: 2026-05-08T21:00:20.973Z
Learnt from: samejr
Repo: triggerdotdev/trigger.dev PR: 3538
File: apps/webapp/app/components/primitives/Resizable.tsx:60-78
Timestamp: 2026-05-08T21:00:20.973Z
Learning: In the triggerdotdev/trigger.dev codebase, treat Zod as a boundary validation tool (API handlers, request/response validation, and storage/DB read/write validation), not as inline render-time validation inside React components/primitive UI code. For render-time guards, prefer small manual type-narrowing checks (e.g., a short predicate like ~10–20 lines) over importing Zod into UI primitives, to avoid per-render schema-parse overhead and unnecessary abstraction. Use the manual guard approach unless you truly need schema validation at a boundary; only then introduce Zod.
Applied to files:
apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx
📚 Learning: 2026-06-25T18:21:55.847Z
Learnt from: carderne
Repo: triggerdotdev/trigger.dev PR: 4039
File: apps/webapp/app/routes/invite-resend.tsx:0-0
Timestamp: 2026-06-25T18:21:55.847Z
Learning: In the triggerdotdev/trigger.dev Zod 4 migration, avoid importing from the root package `conform-to/zod` in webapp code. It can resolve to the Zod 3 build and may crash at module load under Zod 4. When reviewing TypeScript/TSX files in `apps/webapp`, prefer importing from the Zod 4 subpath `conform-to/zod/v4` for Zod 4-compatible schemas/types.
Applied to files:
apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx
📚 Learning: 2026-05-12T21:04:05.815Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 3542
File: apps/webapp/app/components/sessions/v1/SessionStatus.tsx:1-3
Timestamp: 2026-05-12T21:04:05.815Z
Learning: In this Remix + TypeScript codebase, do not flag a server/client boundary violation when a file imports only types from a module matching `*.server`.
Specifically, it’s safe to import types using `import type { Foo } from "*.server"` or `import { type Foo } from "*.server"` because TypeScript erases type-only imports at compile time and they emit no JavaScript, so they won’t cross the Remix server/client bundle boundary.
Only raise the boundary concern for value imports (e.g., `import { Foo }` without `type`, or `import Foo`), since those produce JavaScript output.
Applied to files:
apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx
📚 Learning: 2026-06-25T18:21:51.905Z
Learnt from: carderne
Repo: triggerdotdev/trigger.dev PR: 4039
File: apps/webapp/app/routes/invite-revoke.tsx:0-0
Timestamp: 2026-06-25T18:21:51.905Z
Learning: During the Zod v4 migration in the triggerdotdev/trigger.dev webapp, ensure any imports from `conform-to/zod` use the Zod-4 subpath: `conform-to/zod/v4` (e.g., `import { parseWithZod } from "conform-to/zod/v4"`). Do not import from the package root `conform-to/zod`, because it is the Zod 3 implementation and may load Zod-3-only symbols (e.g., `ZodBranded`, `ZodEffects`), which can throw at module load (notably with `zod4.4.3`). This should be enforced across `apps/webapp/**/*` where helpers like `parseWithZod` and `conformZodMessage` are used.
Applied to files:
apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx
📚 Learning: 2026-07-03T17:10:21.498Z
Learnt from: 0ski
Repo: triggerdotdev/trigger.dev PR: 4148
File: apps/webapp/app/models/orgMember.server.ts:149-168
Timestamp: 2026-07-03T17:10:21.498Z
Learning: In triggerdotdev/trigger.dev, `User.email` (Prisma schema: `internal-packages/database/prisma/schema.prisma`) currently does NOT use `citext` and does NOT have a `lower(email)` functional unique index. Therefore, do not introduce Prisma queries like `where: { email: { equals: <value>, mode: "insensitive" } }` (or any case-insensitive lookup) against `User.email`, because it can force sequential scans of the `users` table under load. During review, ensure email is normalized (e.g., lowercased/trimmed) before both writes and subsequent lookups, and if true case-insensitive behavior/uniqueness is required, implement it via a separate app-wide migration (e.g., switch to `citext` and/or add a functional unique index with backfill) rather than bolting it onto individual feature PRs.
Applied to files:
apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx
📚 Learning: 2026-06-25T18:21:54.729Z
Learnt from: carderne
Repo: triggerdotdev/trigger.dev PR: 4039
File: apps/webapp/app/routes/confirm-basic-details.tsx:0-0
Timestamp: 2026-06-25T18:21:54.729Z
Learning: For Remix + TypeScript files that use Conform v1 (conform-to/react) and its getInputProps helper, when you intend to suppress the helper-provided default value for non-checkbox/non-radio inputs (e.g., hidden inputs managed via an explicit value prop), use the Conform v1 option key `value: false`. Do not recommend `defaultValue: false` here, because `defaultValue` is not a valid option key for these input types in Conform v1 typings.
Applied to files:
apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx
📚 Learning: 2026-06-04T18:16:35.386Z
Learnt from: nicktrn
Repo: triggerdotdev/trigger.dev PR: 3836
File: apps/supervisor/src/backpressure/backpressureMonitor.ts:3-5
Timestamp: 2026-06-04T18:16:35.386Z
Learning: When reviewing TypeScript in this repo, apply the rule “prefer type aliases over interfaces” only to data/object shapes and union/intersection type modeling. If an interface is being used as a behavioral contract for collaborators to implement (e.g., method-shape interfaces that define required behavior, such as `BackpressureLogger` / `BackpressureSignalSource` in `apps/supervisor/src/backpressure/backpressureMonitor.ts`), keep it as an `interface` and do not flag it as a type-alias-vs-interface violation.
Applied to files:
internal-packages/dashboard-agent/src/tool-schemas.ts
📚 Learning: 2026-06-09T17:58:04.699Z
Learnt from: 0ski
Repo: triggerdotdev/trigger.dev PR: 3879
File: apps/webapp/app/models/vercelIntegration.server.ts:619-630
Timestamp: 2026-06-09T17:58:04.699Z
Learning: In this codebase, outbound raw `fetch` calls should typically rely on Node/undici’s default request timeout (about ~300s) rather than adding a per-call `AbortController` + `setTimeout` wrapper inside individual functions (e.g. in files like `apps/webapp/app/models/vercelIntegration.server.ts`). During code review, do not flag the absence of a per-call timeout on a single `fetch` as an issue; if per-call timeouts are needed, they should be implemented via a codebase-wide convention (e.g., a shared fetch wrapper or documented pattern) rather than ad-hoc per-function changes.
Applied to files:
internal-packages/dashboard-agent/src/tool-schemas.ts
🔇 Additional comments (1)
apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx (1)
99-146: LGTM!Also applies to: 245-287
…s pill wins The card's progress line is now the same pill the in-flight tools use, and while an in_progress investigation card is on screen the concurrent tool pill is suppressed.
An AI assistant in a side panel on every dashboard page, behind the dashboard-agent feature flag. It reads runs, errors, queues, deploys and health through the public API (read-only, delegated user token), answers with rich cards, and can keep watching things after the conversation ends.
What's inside
@internal/dashboard-agent-contracts(trigger:// URI grammar, intents, watch specs, block envelope), investigations + watches tables, head-start reliability fix, eval sample-rate gate.get_reportrenders the deterministic health report as a card (metric grid, sparklines, Next steps button row); stale telemetry is flagged and never trusted for advice.DASHBOARD_AGENT_WATCHalert type on the standard channels with one-click unsubscribe; the agent offers, lists and disables subscriptions on request; ungated in-dashboard signal: persistent toast, unread dot on the chat launcher, unread-first history with per-chat status icons.db:seed:agent-examples, with--heartbeat/--degrade/--recoverfor demos).How to review
GUIDEBOOK.md — 10-minute local setup and a hands-on walkthrough of every case. Component gallery at
/storybook/agent-ui.Notes
canAccessDashboardAgent; no behavior change with the flag off.--heartbeatmode is a review-stand crutch and will be removed before merge.